Java for loop problem

I'm making a java program to calculate Simpson's integral rules This is my code Note the second column of numbers in the output value of count = = 4,9,10,11 They are not the numbers I need, they do not follow this pattern I need these figures to be accurate What happened and how should I solve it?

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

Output I get:

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

Solution

Each time you bypass the loop, you mix errors in an imprecise addition of 0.4 to I

Instead, use the integer value of the loop counter and scale it to get a better approximation:

for ( int count = 0; count < 10; ++count ) {
        final double i = 0.4 * count;
        System.out.println ( ( count + 1 ) + " " + i );
    }

This does not eliminate floating point errors, but it means that it does not increase with each iteration To remove errors from the output, format the output to a reasonable number of decimal places:

for ( int count = 0; count < 10; ++count ) {
        final double i = 0.4 * count;
        System.out.printf ( "%2d %.1f\n",( count + 1 ),i );
    }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>