这是我的代码:
import java.util.Scanner;
public class TaylorSeries{
public static int factorial(int num){
if(num == 0) return 1;
return num * factorial(num -1);
}
public static void main(String args[]){
Scanner scanner=new Scanner(System.in);
System.out.println("Enter the number:");
int num = scanner.nextInt();
boolean op_checker = true;
int denom = 0;
double numrad = num * (2 * Math.PI/360);
double sum = 0;
for(int counter = 0; counter < 4; counter++){
denom = counter * 2 + 1;
if(op_checker)
sum += Math.pow(numrad,(double)denom)/factorial(denom);
else sum -= Math.pow(numrad,(double)denom)/factorial(denom);
op_checker = op_checker ? false : true;
System.out.println(sum);
}
System.out.printf("%.4f",sum);
}
}
问题是,当数字非常接近90或更高时,我得到的值是不正确的。谁能帮我理解发生了什么?
答案 0 :(得分:0)
此
sum += sum + Math.pow(...
else sum -= sum + Math.pow(...
应该是
sum += Math.pow(...
else sum -= Math.pow(...
答案 1 :(得分:0)
sum += sum + Math.pow(numrad,(double)denom)/factorial(denom);
应该是
sum = sum + Math.pow(numrad,(double)denom)/factorial(denom);
or
sum += Math.pow(numrad,(double)denom)/factorial(denom);
请注意,您的方法相当无效。要获得下一个系列字词,您可以将最后一个字符乘以(x*x)/((2*i)(2*i+1))
对于大参数值,系列收敛速度很慢 - 这就是您可以看到大错误的原因。您必须获得更多术语(扩展方式)或将参数减少到小范围(推荐)。
另一个可能的错误原因 - 由于整数溢出,您的factorial
函数不适用于大denom
。您可以使用double作为结果或应用我上面描述的更强大的算法。
答案 2 :(得分:0)
package algorithms;
public class TaylorSeries {
public static double factorial(double num){
if(num == 0) return 1;
return num * factorial(num -1);
}
public static void main(String args[]){
int[] radians = {0, 23, 45, 75, 90, 100, 120, 150, 180, 275, 360};
for (int num : radians) {
double denom = 0;
double numrad = num * (2 * Math.PI/360);
double sum = 0;
int sign = 1;
for(int counter = 0; counter < 9; counter++){
denom = counter * 2 + 1;
double value = Math.pow(numrad, denom);
sum += sign * Math.pow(numrad,denom)/factorial(denom);
sign *= -1;
}
System.out.print(" Angle is: " + num + " = ");
System.out.printf("%.4f",sum);
System.out.println();
}
}
}
编辑:
输出:
Angle is: 0 = 0.0000
Angle is: 23 = 0.3907
Angle is: 45 = 0.7071
Angle is: 75 = 0.9659
Angle is: 90 = 1.0000
Angle is: 100 = 0.9848
Angle is: 120 = 0.8660
Angle is: 150 = 0.5000
Angle is: 180 = 0.0000
Angle is: 275 = -0.9961
Angle is: 360 = 0.0110