Java for-loop problem

I am making a Java program to compute the Simpson rule for integrals. Here is the code I have. Note the second column of numbers in the output values ​​count == 4,9,10,11. These are not the numbers I need, they do not follow the pattern. I need these numbers to be accurate. What is happening and how can I fix 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;
}

I get the output:

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
+3
source share
8 answers

Every time you go around the loop, you mix the error in the inaccurate addition of 0.4 to i.

Instead, use the integral value for the loop counter and scale it to get a better approximation to the values:

    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 );
    }
+7
+6

.

, . java.text.DecimalNumberFormat .

+4

, , , , , , . 1 , ... , java.

+1
+1

, , , , . , , :

 if (f1 == 0.0 || f1 == 4.0)

. , , , 3.9999 4.0001.

, , count, int. . , .

+1

:

System.out.printf("%.1f", Math.E); // prints 2.7
System.out.printf("%.2f", Math.E); // prints 2.72
System.out.printf("%.3f", Math.E); // prints 2.718

strictfp

+1

From your loop condition, it seems you don't want line 11 to be processed at all. I recommend that you use the index of whole loops and use it to calculate the values ​​you pass to Sfunction. The following should be equivalent to what you have (except that it goes off line 11).

double totalS = 0.0;

for( int i = 1; i <= 10; i++ )
{
    double f1 = 0.4 * (i - 1);
    totalS += Sfunction(f1, i);
    System.out.println(i + " " + f1 + " " + totalS);
}

Your print accuracy problem can be solved with DecimalFormat as suggested in other answers.

+1
source

Source: https://habr.com/ru/post/1730801/


All Articles