Taylor Series of a Sine

隐身守侯 提交于 2020-01-07 08:29:11

问题


I'm currently in a Java class at my university and we've been asked to code a Taylor Series equation to compute a Sine function. I've coded what makes sense to me, and I've tried debugging every section of code I can think of to make sure all of the parts are functioning the way I think they should, but the program still isn't functioning right. So, I'm hoping someone might look at this and spot what I'm doing wrong.

this is the equation: Taylor Series Equation

public class Sine {

public static int factorial(int a) {
    int num = a;
    if (a == 1) return 1;
    for (int i = 1; i < num; i++){
    a = a * i;
    }   return a;
}
public static double numerator(double x, int power) {
    double ret = Math.pow(x, power);
    return ret;
    }
public static void main(String[] args) {
    int power = 1;
    int iter = 0;
    double x = Math.PI/4;

    int sign = 1;
    while (iter != 10) {
        iter++;
        System.out.println("Iteration " + iter + ": " + x);
        x += sign * numerator(x, power)/factorial(power);
        power += 2;
        sign *= -1;
    }
    System.out.println("\nTaylor Series, Final: " + x);
System.out.println("Value of Sine: " + Math.sin(Math.PI/4));
}
}

I'm just very confused what's going on and why it's not working.


回答1:


What you're doing wrong (thanks @AndyTurner) is trying to store large factorials in an int, which of course can only store numbers up to about 2 billion.

To avoid having to deal with large numbers and their limited accuracies, you could use the following principle, that applies to the Taylor series for sines.

Term in xn = (Term in xn-2) * - x * x / n / (n-1).

For example, if you've already calculated x5 / 5!, then the best way to calculate -x7 / 7! is to multiply the number you've already calculated by -x2 / 6 / 7.

If you calculate your terms this way, then add them up, you avoid all the problems that come with dealing with large numbers.



来源:https://stackoverflow.com/questions/44813627/taylor-series-of-a-sine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!