我試圖用泰勒近似來評估1.89的sin的近似值。我將輸出與Math.sin(x)的值進行了比較;然而,在大約14個術語之後,我的價值偏離很大並且變得錯誤。我嘗試了x的較小值(< 0.5)的近似值,並且這些值相匹配。使用20項計算sin(x)的近似值
我只是想弄清楚爲什麼在Mac OSx上使用崇高和通過bash編譯的Java偏離了真正的輸出。
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;
}
}
嘗試打印出''n'的'factorial'函數的結果。 –
@AndyTurner,感謝您的建議,我將運行一個循環,並比較以查看函數是否按預期工作,我嘗試了單點值並在初始停止 – Diante