有人可以帮我找出这个犯罪代码(x)裁缝功能以获取以下内容:
public static double MySinApproximate( double x)
?这就是我到目前为止所得到的,它必须以这种方式!
import java.lang.Math;
public class mysin {
public static void main(String[] args){
double x= Math.PI;
System.out.println( MySin(x) + "\t \t" + Math.sin(x) + "\n" );
}
public static double MySin(double x){
double sumNeu, sumOld, sum;
int i = 1;
sum = sumNeu = x; // This should calculating the first term Value
do //the loop do will calculating the Tailor Series
{
sumOld = sumNeu;
i++; sum = + sum * x * x / i;
i++; sum = sum / i;
sumNeu = sumOld + sum;
}
while( sumNeu != sumOld);
return sumNeu;
}
} // 11.548739357257745 1.2246467991473532E-16 (as output)
答案 0 :(得分:1)
您的循环未正确计算Taylor series。 (这实际上是Maclaurin series,这是泰勒系列的特殊情况,其中a = 0.)对于正弦函数,需要以交替的方式添加和减去这些术语。
sin(x)= x - x 3 / 3! + x 5 / 5! - ......
您的方法只会添加条款。
sin(x)= x + x 3 / 3! + x 5 / 5! + ...
通过添加指定的行,在每次迭代时翻转sum
的符号:
do // The loop will calculate the Taylor Series
{
sumOld = sumNeu;
i++; sum = + sum * x * x / i;
i++; sum = sum / i;
sum = -sum; // Add this line!
sumNeu = sumOld + sum;
}
通过此更改,我得到的结果非常接近:
2.3489882528577605E-16 1.2246467991473532E-16
由于Java中的浮点数学(以及一般的IEEE)固有的不精确性,这可能与您编写自己的正弦方法一样接近。
我测试了另外一个π/ 2的情况:
System.out.println( MySin(x/2) + "\t \t" + Math.sin(x/2) + "\n" );
再次,它很接近:
1.0000000000000002 1.0
答案 1 :(得分:0)
1.我想再写一遍 - 我尝试从正弦泰勒写出前4个系列,并且所有人都在一起,但无论如何都不能正常工作 - 3.i得到这个输出
0.0 0.8414709848078965
0.8414709848078965 0.9092974268256817
0.8414709848078965 0.1411200080598672
0.9092974268256817 -0.7568024953079282
4.我如何才能获得相同的准确度
1.0000000000000002 1.0
和正弦系列(x)?
public class MySin {
public static void main(String[] args){
double y = 0;
y = 4;
for (int i = 1; i<= y; i++){
System.out.println( MySin(i/2) + "\t \t" + Math.sin(i) + "\n" );
}
}
public static double MySin(double x){
double sumNew, sumOld, sum;
int i = 1;
sum = sumNew = x; // This should calculating the first term Value
do //the loop do will calculating the Tailor Series
{
sumOld = sumNew;
i++; sum = - sum * x * x / i; // i did change the sign to -
i++; sum = sum / i;
sum = - sum; // so i don't need this line anymore
sumNew = sumOld + sum;
}
while( sumNew != sumOld);
return sumNew;
}
public static double MySineProximity ( double x) {
while ( x <= ( Math.PI /2 ) )
{
x = 0;
}
return MySin (x);
}
}