我正在编写一个 Java 程序来计算辛普森积分法则。这是我的代码。请注意 count == 4,9,10,11 的输出值中的第二列数字。它们不是我需要的数字,它们不遵循模式。我需要这些数字是准确的。这是怎么回事,我该如何解决?
public static void main(String[] args)
{
double totalS = 0.0;
int count = 0;
for(double i=0; i< 4; i += 0.4 )
{
count++;
totalS += Sfunction(i, count);
System.out.println(count + " " + i + " " + totalS);
}
}
public static double Sfunction(double f1, int count)
{
double value;
if (f1 == 0.0 || f1 == 4.0)
value = Math.cos(Math.sqrt(f1));
else if ((count % 2) == 1)
value = 2 * Math.cos(Math.sqrt(f1));
else
value = 4 * Math.cos(Math.sqrt(f1));
return value;
}
我得到的输出是:
1 0.0 1.0
2 0.4 4.226313639540303
3 0.8 5.478244888601832
4 1.2000000000000002 7.30884788480188
5 1.6 7.911122809972827
6 2.0 8.534897589034324
7 2.4 8.578100205110182
8 2.8 8.168723348285942
9 3.1999999999999997 7.736055200662704
10 3.5999999999999996 6.452869366954546
11 3.9999999999999996 5.620575693860261
最佳答案
每次循环时,都会将 0.4 不精确地加到 i 中的错误加起来。
相反,为循环计数器使用整数值,并对其进行缩放以获得更好的近似值:
for ( int count = 0; count < 10; ++count ) {
final double i = 0.4 * count;
System.out.println ( ( count + 1 ) + " " + i );
}
这不会消除浮点误差,但意味着它不会在每次迭代中增加。要从输出中删除错误,请将输出格式化为合理的小数位数:
for ( int count = 0; count < 10; ++count ) {
final double i = 0.4 * count;
System.out.printf ( "%2d %.1f\n", ( count + 1 ), i );
}
关于java for循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2173984/