gpt4 book ai didi

java - 如何在 Java 中重新实现 sin() 方法? (使结果接近 Math.sin() )

转载 作者:搜寻专家 更新时间:2023-11-01 01:14:34 24 4
gpt4 key购买 nike

我知道 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;
}

最佳答案

您应该使用泰勒级数。很棒的教程here

我看你试过了但是你的sin方法不对


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;
}

计算 sin function 的工作示例.抱歉,我用 C++ 记下了它,但希望您能理解。没什么不同:)

关于java - 如何在 Java 中重新实现 sin() 方法? (使结果接近 Math.sin() ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6242369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com