我试图使用泰勒近似来评估1.89的sin的近似值。我将输出与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;
}
}
答案 0 :(得分:2)
建议使用BigDecimal
代替double
和int
进行大数值计算,例如阶乘和幂。
答案 1 :(得分:1)
原因在于:
public static int factorial(int n) {
int result = 1;
while (n >= 1) {
result = result * (n);
n--;
}
return result;
}
你没有考虑这样一个事实:阶乘收敛非常快,产生溢出(有些结果是负数)
你可以验证那个。拆分使用factorial返回值的代码:
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