在Allen B. Downey的“Think Java”中,我被问到7.6。该问题要求在不使用阶乘或指数函数的情况下评估e^{(-x)^2}
。我得到的代码适用于x = 2,但没有其他数字。
public static double gauss2(double x, double n) {
double i = 2;
double count = n;
double num = 1;
while (i <= n){
num = ((x*x)/(i - 1))*num;
i = i + 1;
}
if (n == 1) {
return 1;
}
else if (n%2 == 0) {
return num*(-1) + gauss2(x,n-1);
}
else {
return num + gauss2(x, n-1);
}
答案 0 :(得分:0)
The Maclaurin series for ex很有用。它是:
e x =Σ{n = 0到∞}(x n / n!)
因此,获得近似结果的一些简单代码是:
public final class Exponential {
private static final int ITERATIONS = 32;
public static final double exp(final double x) {
double power = 1.0;
double factorial = 1.0;
double result = 1.0;
for (int n = 1; n <= ITERATIONS; n++) {
power *= x;
factorial *= n;
result += power/factorial;
}
return result;
}
public static final void main(String[] args) {
System.out.println("Testing Math.exp against Exponential.exp for a few inputs");
for (double exponent = -5.0; exponent <= 5.0; exponent += 0.1) {
System.out.printf("e^%f = %f = %f\n", exponent, Math.exp(exponent), exp(exponent));
}
}
}
然后,您可以使用exp((-x)*(-x))
。