我正在尝试在不使用Java中使用Math.sin()的情况下计算角度的正弦 [英] I am trying to calculate sine of an angle without using the Math.sin() in java

查看:318
本文介绍了我正在尝试在不使用Java中使用Math.sin()的情况下计算角度的正弦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试不使用Math.sin()来计算角度的正弦值.我一直陷在方程式中,因为我不断得到错误的结果

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;

}

推荐答案

您似乎正在尝试使用

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! + ...

您的初始answer应该是x时是1.您的初始power应该是x,也应该是1.

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;

出于某种原因,您本不应该添加一个到结果的power部分.

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

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

您还需要修正factorial计算.乘以n + 1n,而不是n + 1n - 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

请注意,随着x的值变大,这将变得更加不准确,这不仅是因为表示pi的不准确,而且还因为要计算用于添加和减去大值的浮点数.

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.

这篇关于我正在尝试在不使用Java中使用Math.sin()的情况下计算角度的正弦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆