java求正弦,我正在尝试在不使用Java中使用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! + ...

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值