我编写了这段代码来计算角度的正弦值。这适用于较小的角度,例如 +-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);
}
}