計算pow
とfactorial
この方法は非常にコストがかかり、丸め誤差が発生しやすくなります。ところで、私はあなたが意味しfactorial(i)
ないと思います(x)
public static double sin(double x, int n) {
double result = x;
double term = x;
for (int i = 3, n2 = n * 2; i <= n2; i += 2) {
term *= -x * x / ((i - 1) * i);
result += term;
}
return result;
}
public static void main(String... args) {
/*
for (int i = -20; i <= 20; i++) {
double d = i / 10.0;
System.out.println(Math.sin(d) + " vs " + sin(d, 14));
}
*/
double d = -1.5;
double sin = Math.sin(d);
System.out.println("Searching for sin(" + d + ") = " + sin);
for (int n = 2; n <= 14; n++) {
System.out.println(n + ": " + sin + " vs " + sin(d, n) + " err: " + (sin(d, n) - sin));
}
}
プリント
Searching for sin(-1.5) = -0.9974949866040544
2: -0.9974949866040544 vs -0.9375 err: 0.059994986604054446
3: -0.9974949866040544 vs -1.00078125 err: -0.00328626339594551
4: -0.9974949866040544 vs -0.9973911830357143 err: 1.0380356834016613E-4
5: -0.9974949866040544 vs -0.9974971226283482 err: -2.1360242937751295E-6
6: -0.9974949866040544 vs -0.9974949556821353 err: 3.092191913633968E-8
7: -0.9974949866040544 vs -0.9974949869361672 err: -3.321127817201841E-10
8: -0.9974949866040544 vs -0.9974949866013026 err: 2.751798788835913E-12
9: -0.9974949866040544 vs -0.9974949866040727 err: -1.8207657603852567E-14
10: -0.9974949866040544 vs -0.9974949866040544 err: 0.0
11: -0.9974949866040544 vs -0.9974949866040546 err: -1.1102230246251565E-16
12: -0.9974949866040544 vs -0.9974949866040546 err: -1.1102230246251565E-16
13: -0.9974949866040544 vs -0.9974949866040546 err: -1.1102230246251565E-16
14: -0.9974949866040544 vs -0.9974949866040546 err: -1.1102230246251565E-16