【发布时间】:2018-06-23 10:32:14
【问题描述】:
我正在尝试构建一个计算 sin(x) 的泰勒级数的程序。 x 大于 0 且小于 pi/2(我尝试用乳胶写但没有用(??))。 sin(x) 的近似值在点 x0 = 0 附近。e 是最大误差(或不准确......我不知道它是如何调用的)。误差(或不准确性)是用我称为 r 的方法中的公式计算的。所以 r 必须总是小于 e。最后,n 是迭代次数。下面是我的程序,它没有错误,但我得到不准确的结果,我不知道我做错了什么(也许我们应该考虑使用有错误的公式的可能性)。
import java.lang.Math;
import java.util.Scanner;
public class hw74 {
public static long factorial(int number) {
long result = 1;
for (int factor = 2; factor <= number; factor++) {
result *= factor;
}
return result;
}
static double p(double x, double x0, int n) {
double PT = Math.pow(-1, n) * (Math.pow(x-x0, 2*n+1)/factorial(2*n+1));
return PT;
}
static double r(double x, int n) {
double rn = Math.pow(x, n+1)/factorial(n+1);
return Math.abs(rn);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double x0 = 0;
System.out.println("Give x. ");
double x = sc.nextDouble();
System.out.println("Give E. ");
double e = sc.nextDouble();
System.out.println("Give N. ");
int n = sc.nextInt();
int i = 0;
//System.out.println(e<r(x, i) && i<n);
//System.out.println(r(x, i));
while((r(x, i)<e) && i<n) {
i++;
System.out.println("N is : "+i);
System.out.println("P is : "+p(x,x0,n));
System.out.println("E is : "+r(x,n));
}
}
}
例如:对于 n=5, e=1 和 x=pi/5 (0.62831853071),结果应该是:sin(pi/5) = 0.5877852522... 对于 n=1 r=0.1974, n= 2 r=0.0413, n=3 r=0.0065, n=4 r=8.16*10^(-4), n=5 r=8.54*10^(-5)
【问题讨论】:
-
不建议像您那样通过调用阶乘来编写公式。它不准确且效率低下。
-
@duffymo 所以我应该计算相同方法中数字的阶乘?但是,到目前为止,这不会导致任何问题...
-
我没有说“问题”——不准确且效率低下。
标签: java math taylor-series