use*_*501 4 java math trigonometry
我知道Math.sin()可以工作,但我需要自己实现它使用factorial(int)我已经下面的因子方法是我的sin方法但我不能得到相同的结果Math.sin():
public static double factorial(double n) {
if (n <= 1) // base case
return 1;
else
return n * factorial(n - 1);
}
public static double sin(int n) {
double sum = 0.0;
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) {
sum += Math.pow(1, i) / factorial(2 * i + 1);
} else {
sum += Math.pow(-1, i) / factorial(2 * i + 1);
}
}
return sum;
}
Run Code Online (Sandbox Code Playgroud)
你应该使用泰勒系列.一个伟大的教程在这里
我可以看到你已经尝试但你的罪恶方法是不正确的
public static sin(int n) {
// angle to radians
double rad = n*1./180.*Math.PI;
// the first element of the taylor series
double sum = rad;
// add them up until a certain precision (eg. 10)
for (int i = 1; i <= PRECISION; i++) {
if (i % 2 == 0)
sum += Math.pow(rad, 2*i+1) / factorial(2 * i + 1);
else
sum -= Math.pow(rad, 2*i+1) / factorial(2 * i + 1);
}
return sum;
}
Run Code Online (Sandbox Code Playgroud)
计算sin函数的工作示例.对不起,我已经用C++记下了它,但希望你能得到它.它不是那么不同:)