2

我编写了这段代码来计算角度的正弦值。这适用于较小的角度,例如 +-360。但是随着更大的角度,它开始给出错误的结果。(当我说更大时,我的意思是在 +-720 或 +-1080 范围内)

为了获得更准确的结果,我增加了循环运行的次数。这给了我更好的结果,但仍然有其局限性。

所以我想知道我的逻辑是否有任何错误,或者我是否需要摆弄循环的条件部分?我怎样才能克服我的代码的这个缺点?内置的 java 正弦函数为我测试过的所有角度提供了正确的结果。那么我哪里出错了?

也有人可以告诉我如何修改循环的条件,以便它运行直到我获得所需的十进制精度?

import java.util.Scanner;


class SineFunctionManual 
{
    public static void main(String a[])
    {
        System.out.print("Enter the angle for which you want to compute sine : ");

        Scanner input = new Scanner(System.in);
            int degreeAngle = input.nextInt();  //Angle in degree.
        input.close();

        double radianAngle = Math.toRadians(degreeAngle);   //Sine computation is done in terms of radian angle
        System.out.println(radianAngle);
        double sineOfAngle = radianAngle,prevVal = radianAngle; //SineofAngle contains actual result, prevVal contains the next term to be added
        //double fractionalPart = 0.1;  // This variable is used to check the answer to a certain number of decimal  places, as seen in the for loop

        for(int i=3;i<=20;i+=2)
        {
            prevVal = (-prevVal)*((radianAngle*radianAngle)/(i*(i-1)));     //x^3/3! can be written as ((x^2)/(3*2))*((x^1)/1!), similarly x^5/5! can be written as ((x^2)/(5*4))*((x^3)/3!) and so on. The negative sign is added because each successive term has alternate sign.
            sineOfAngle+=prevVal;

            //int iPart = (int)sineOfAngle;
            //fractionalPart = sineOfAngle - iPart; //Extracting the fractional part to check the number of decimal places.
        }

        System.out.println("The value of sin of "+degreeAngle+" is : "+sineOfAngle);

    }

}
4

2 回答 2

4

对于大的正值和大的负值,正弦的多项式逼近差异很大。请记住,因为在所有实数上从 -1 到 1 不等。另一方面,多项式,特别是具有更高阶的多项式,不能做到这一点。

我建议使用正弦的周期性对您有利。

int degreeAngle = input.nextInt() % 360;

即使对于非常非常大的角度,这也将给出准确的答案,而不需要荒谬的术语。

于 2013-11-09T04:59:56.977 回答
1

距离 越远x=0,您需要的泰勒展开项就越多sin x,以达到正确答案的特定精度。您将在第 20 项左右停止,这对于小角度来说很好。如果您想获得更大角度的更好精度,您只需要添加更多项。

于 2013-11-09T05:00:53.237 回答