使用 20 项计算 sin(x) 的近似值

  • 本文关键字:近似值 sin 计算 使用 java
  • 更新时间 :
  • 英文 :


我正在尝试使用泰勒近似来评估 1.89 的罪恶近似值。我将输出与 Math.sin(x( 的值进行了比较;然而,在大约 14 个学期后,我的价值观在很大程度上偏离并变得错误。我尝试了较小值 x (<0.5( 的近似值,并且值匹配。

我只是想弄清楚为什么Java,使用sublime并通过Mac OSx上的bash遵守偏离了真正的输出。

public class Test {
public static void main (String[] args) {
double x = 1.89;
double sinx = 0;
int n = 20;
int countOdd = 1;
int counter = 1;
int result = 0;
int value = 0;
while (countOdd <= n) {
if (counter%2 != 0) {
// Even term odd number
if (countOdd%2 == 0) {
sinx = sinx - (Math.pow(x,counter)/(double)factorial(counter));
System.out.println(" counter even odd term  = " + countOdd);
countOdd++;
System.out.println(" sinx  = " + sinx);
}
// Odd term odd number
else {
sinx = sinx + (Math.pow(x,counter)/(double)factorial(counter));
System.out.println(" counter odd odd term  = " + countOdd);
countOdd++;
System.out.println(" sinx  = " + sinx);
}
}
// Update the result and reset the value
//sinx = sinx + value;
//value = 0;
System.out.println(" counter  = " + counter);
counter++;
}
System.out.println(" sinx  = " + sinx);
System.out.println(" sinx from math library = " + Math.sin(x));
}
/** calcutes and returns  n! 
@param n : a positive integer number
@return n!
*/
public static int factorial(int n)
{
// your code goes here
int result = 1; // if n = 0, while loop is by passed and 0 is returned
while (n >= 1) {
result = result * (n);
n--;
}
return result;
}
}

建议使用BigDecimal而不是doubleint进行阶乘和幂等大型数值计算。

原因在这里:

public static int factorial(int n) {
int result = 1;
while (n >= 1) {
result = result * (n);
n--;
}
return result;
}

您没有考虑阶乘收敛非常快产生溢出的事实(有些结果是负数(

您可以验证 beh. 稍微拆分使用阶乘返回值的代码:

while (countOdd <= n) {
if (counter % 2 != 0) {
// Even term odd number
if (countOdd % 2 == 0) {
int factorial = factorial(counter);
System.out.println("factorial: " + factorial);
sinx = sinx - (Math.pow(x, counter) / factorial);
System.out.println(" counter even odd term  = " + countOdd);
countOdd++;
System.out.println(" sinx  = " + sinx);
}
// Odd term odd number
else {
int factorial = factorial(counter);
System.out.println("factorial: " + factorial);
sinx = sinx + (Math.pow(x, counter) / factorial);
System.out.println(" counter odd odd term  = " + countOdd);
countOdd++;
System.out.println(" sinx  = " + sinx);
}
}

正如您将注意到的,输出将产生负值,这些负值正在分发您想要实现的数字近似值

...
counter even odd term  = 10
sinx  = 0.9476740866450655
counter  = 19
counter  = 20
factorial: -1195114496

最新更新