这些函数通常给出结果的无理数,并且可能是通过泰勒系列计算的,但是有没有关于这些系列重复多少次的文档? 我在想这是不是罪:
public double sin(double x,int n){
double res = 0;
for (int i=0;i<n;i++){
res+=Math.pow(x,i)/this.factorial(x);
}
return res;
}
n
应该是什么?
我需要这个,因为我需要自己创建数学函数,所以我应该知道应该多少次重复这些操作。
感谢
答案 0 :(得分:9)
对于Java 6,Math
库将其多个调用(包括cos
)委托给StrictMath
,该类调用在类文档中说明:
这些算法可以从着名的网络库netlib获得,作为“Freely Distributable Math Library”软件包,fdlibm。
答案 1 :(得分:4)
答案 2 :(得分:3)
基本的想法是你不断重复,直到双重不再改变,因为你添加的精度太小而不能用双精度表示。
答案 3 :(得分:2)
以这种方式计算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