I am trying to calculate sine of an angle without using the Math.sin() in java

无人久伴 提交于 2019-12-11 17:54:38

问题


I am trying to calculate sine of an angle without using the Math.sin(). I got stuck in it's equation as I keep getting the wrong results

note I have a method that changes the angle from degrees to radians

public static double sin(double x, int precision) {
 //this method is simply the sine function
    double answer = 1, power = 1;
    int n = 2,factorial = 1;

    while (n<=precision) {

        power = (power * x * x *-1) +1 ; 
        factorial = (factorial * (n +1))* (n-1);
          answer = answer + ((power/factorial ));

        n = n + 2;

    }

    return answer;

}

回答1:


It looks like you're attempting to calculate the sine of angle given in radians using the Maclaurin series, a special case of Taylor series.

sin(x) = x - x^3/3! + x^5/5! - x^7/7! + ...

Your initial answer is 1 when it should be x. Your initial power is 1 when it should be x also.

double answer = x, power = x;

For some reason you're adding one to the power part of the result when you shouldn't be.

power = (power * x * x * -1);

You'll also need to fix your factorial calculation. Multiply by n + 1 and n, not n + 1 and n - 1.

factorial = (factorial * (n + 1)) * (n);

With these fixes, testing:

for (double angle = 0; angle <= Math.PI; angle += Math.PI / 4)
{
    System.out.println("sin(" + angle + ") = " + sin(angle, 10));
}

The results are pretty good considering the limitations of precision for floating point arithmetic.

sin(0.0) = 0.0
sin(0.7853981633974483) = 0.7071067811796194
sin(1.5707963267948966) = 0.999999943741051
sin(2.356194490192345) = 0.7070959900908971
sin(3.141592653589793) = -4.4516023820965686E-4

Note that this will get more inaccurate as the values of x get larger, not just because of the inaccuracy to represent pi, but also because of the floating point calculations for adding and subtracting large values.



来源:https://stackoverflow.com/questions/49435077/i-am-trying-to-calculate-sine-of-an-angle-without-using-the-math-sin-in-java

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