45.3 Special Functions
Special functions arise in probability, statistics, and physics. Java lacks built-ins; implement or use libraries.
45.3.1 Gamma Function
Γ(n) = (n-1)! for integers; extends factorial to reals.
// Stirling's approximation (rough)
double gamma(double x) {
return Math.sqrt(2 * Math.PI / x) * Math.pow(x / Math.E, x);
}
// For production, use Apache Commons Math or similar
45.3.2 Error Function (erf)
Used in probability (normal distribution CDF).
// Abramowitz & Stegun approximation
double erf(double x) {
double a1 = 0.254829592;
double a2 = -0.284496736;
double a3 = 1.421413741;
double a4 = -1.453152027;
double a5 = 1.061405429;
double p = 0.3275911;
int sign = x < 0 ? -1 : 1;
x = Math.abs(x);
double t = 1.0 / (1.0 + p * x);
double y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t * Math.exp(-x*x);
return sign * y;
}
Complement: erfc(x) = 1 - erf(x)
45.3.3 Bessel Functions
Solutions to Bessel's differential equation; appear in wave propagation.
// J₀(x) series expansion (small x)
double besselJ0(double x) {
double sum = 1.0;
double term = 1.0;
for (int k = 1; k < 20; k++) {
term *= -(x*x) / (4.0 * k * k);
sum += term;
if (Math.abs(term) < 1e-10) break;
}
return sum;
}
For robust implementations, use specialized libraries (Apache Commons Math, JAMA).
45.3.4 Library Recommendations
- Apache Commons Math: comprehensive special functions
- JScience: physics/engineering functions
- Colt: high-performance scientific computing