简体   繁体   中英

How to evaluate e^{(-x)^2} in java?

In "Think Java" by Allen B. Downey, I am stuck on question 7.6. The question asks to evaluate e^{(-x)^2} without using factorial or exponent functions. I got the code working for x = 2, but not other numbers.

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);
    }

The Maclaurin series for e x is useful. It goes:

e x = Σ{n = 0 to ∞} (x n /n!)

So, some simple code to get approximate results is:

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));
        }
    }
}

You can then use exp((-x)*(-x)) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM