有趣的問題。 像Tatarize一樣,我希望這不是功課迴避。
該代碼看起來預示了在所有角度0-90度的結果中給出+/- 0.000 000 1的絕對精度所需的術語數。
功率最高的術語會使x^k/k有所不同!到結果。 所以
x^k/k! < 1/10^7
x是弧度那麼X〜1.57拉德的最大價值。 這意味着只有一系列的權力13纔會給你一個小於0.000 000的最終期限1。
不幸的是我的電腦是高級的(32位)和任何計算13的嘗試!導致溢出。所以我適應Horner method了一下,也許失去一些效率,而且避免了階乘溢出並允許停止,如果角度小,或者如果足夠的精度,功率之前獲得13
Sin x = x - x^2(x/3! - x^2(x/5! - x^2(x/7! - . . . - x^2(x/(m-1)!- x^2(x/m!)
其中最高的功率需要對於m所需的絕對精度。
Sin x = x + Sum { iTerm(i) * x^2/(i * (i-1)) }
其中
iTerm(0) = x and iTerm(n) = - x^2 * iTerm(n-1)/(i*(i-1)
PS - 爲什麼我們不能用數學堆棧交易所以外數學格式? 這會使寫作方程式變得更清晰。
public class TrigByPoly
{
// No constructor used.
public static void main(String[] args)
{
double x0 = 0,
x1 = Math.PI/12,
x2 = Math.PI/6,
x3 = Math.PI/4,
x4 = Math.PI/3,
x5 = Math.PI/2;
double sinx0 = SinByPoly(x0),
sinx1 = SinByPoly(x1),
sinx2 = SinByPoly(x2),
sinx3 = SinByPoly(x3),
sinx4 = SinByPoly(x4),
sinx5 = SinByPoly(x5);
System.out.println("Sin(0) to 7 decimal places is : " + sinx0);
System.out.println("Sin(15) to 7 decimal places is : " + sinx1);
System.out.println("Sin(30) to 7 decimal places is : " + sinx2);
System.out.println("Sin(45) to 7 decimal places is : " + sinx3);
System.out.println("Sin(60) to 7 decimal places is : " + sinx4);
System.out.println("Sin(90) to 7 decimal places is : " + sinx5);
}
public static double SinByPoly(double x)
{
int i = 0; // Polynomial order indicator.
double x2 = x * x,
iTerm,
sinx = 0;
if (x < 0.0084) // Limiting angle for Sinx = x to 10^-7 precision.
sinx = x;
else
{
sinx = x;
iTerm = sinx;
i = 3;
do
{
iTerm = - x2 * iTerm/(i * (i - 1));
sinx += iTerm;
i = i + 2;
} while (i < 14 && (iTerm > 0.0000001 || -iTerm > 0.0000001));
}
return sinx;
}
}
OUTPUT
======
Sin(0) to an absolute precision of 1.0E-7 is : 0.0
Sin(15) to an absolute precision of 1.0E-7 is : 0.2588190618109834
Sin(30) to an absolute precision of 1.0E-7 is : 0.4999999918690232
Sin(45) to an absolute precision of 1.0E-7 is : 0.7071067829368671
Sin(60) to an absolute precision of 1.0E-7 is : 0.8660254450997811
Sin(75) to an absolute precision of 1.0E-7 is : 0.9659258210120795
Sin(90) to an absolute precision of 1.0E-7 is : 0.999999943741051
你有一個無限循環,因爲你的條件不是你想要的。您可能試圖重複使用變量來實現2個不同的目的並失敗。創建一個delta變量,用於存儲在此迭代中所做的更改並在條件中測試detla值。 – HopefullyHelpful