2008-10-27 63 views
2

我必須在我的Comp Sci類中從頭開始創建sin函數,並且我正在接近解決方案。但是,我仍然有一些問題。如果我輸入一個.5PI或更低的值,它會起作用,否則我會得到不正確的結果。這裏是我的代碼至今:在Java中製作自定義Sin()函數

double i=1; 
double sinSoFar = 0; 
int term = 1; 
while(i >= .000001) 
{ 
    i = pow(-1, term + 1) * pow(sinOf, 2*term-1)/factorial(2*term-1); 
    sinSoFar=sinSoFar + i; 
    term++; 
} 

回答

5

就像Federico指出的那樣,問題可能在於factorial()或pow()。我跑了一個測試,工作正常與Math類中提供的POW()函數替換你的職責,這階乘():

public static long factorial(long n) { 
     if  (n < 0) throw new RuntimeException("Underflow error in factorial"); 
     else if (n > 20) throw new RuntimeException("Overflow error in factorial"); 
     else if (n == 0) return 1; 
     else    return n * factorial(n-1); 
} 
3

一些建議:

  • 開始與長期= 0的規範麥克勞林擴張也確實
  • 計算的權力和階乘,而你是循環(即,在每一步更新它們)。也許問題在pow()或factorial()中。

編輯。建議:一旦已經計算第k項,就可以計算第(k + 1)個一個接:

  • 由(-1)
  • 乘以sinOf^2
  • 劃分乘法由(2K + 2)(2K + 3)

這樣就可以完全避免權力和階乘的計算。

0

至於值0以外 - 1/2PI,它們都可以從範圍內的值計算。

// First, normalize argument angle (ang) to -PI to PI, 
// by adding/subtracting 2*PI until it's within range 
if (ang > 1/2PI) { 
    sin = sin (PI - ang); 
} 
else if (ang < 0) { 
    sin = -1 * sin(-1 * ang); 
} 
else { 
    // your original code 
}