Search code examples
javataylor-series

Taylor series. Program does fewer iterations


So I am required to recursively calculate e^x using a factored form of a Taylor series:

equation: e^x = 1 +x + (x^2)/2! + ... + ((x^n)/n!))

U(n) = U(n-1)*(x/n)

break point |U(n)| < eps

package lab2;
import java.util.Scanner;

public class Lab2 {
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner in = new Scanner(System.in);
        System.out.println("Enter x: ");
        int x = in.nextInt();
        System.out.println("Enter 0 < e < 1: ");
        double e = in.nextDouble();
        double result = 1.0;
        int n = 1;
        double U = x / n;
        while (Math.abs(U) >= e)
        {
            double fa = 1;
            for (int i = 1; i <= n; i++)
                fa *= i;
            result += Math.pow(x, n) / fa;
            U *= x / ++n;
        }
        System.out.println("e^x = " + result);
    } 
}

It works only x+1 times and then debug says U equals 0 and its our break point. I can't get why this happens. Can you please help me?


Solution

  • Since x and n are integer, dividing them will be done using integer division. Only after the division is down is the result promoted to a double in order to store in U. In order to perform floating point division you could either define x as a double or explicitly cast it when you divide:

    double U = ((double) x) / n;