Integration using the Trapezoid rule in C gives the wrong answer for certain values

I wrote some code to integrate the function 5x ^ 4 + 4x ^ 3 + 3x ^ 2 + 2x + 1.

#include<stdio.h>
#include<math.h>

float func(float x){
    float a;
    a = 5*pow(x,4) + 4*pow(x,3) + 3*pow(x,2) + 2*x +1;
    return a;
}

int main(){ 
    float numberOfXValues;
    float a = 0;            //lower limit
    float b = 1;            //upper limit
    float numberOfStrips;
    float stripSize;
    float finalAnswer;
    float sumFirstAndLast;  //summation of first and last x value

    while(1){
        printf("Input number of X values:");
        scanf("%f", &numberOfXValues);

        numberOfStrips = numberOfXValues - 1;
        stripSize = (b - a)/(numberOfStrips);                      
        sumFirstAndLast = 0.5*func(a) + 0.5*func(b);

        for (float z = stripSize; z < b; z += stripSize ){
            sumFirstAndLast += func(z);
        }

        finalAnswer = sumFirstAndLast * stripSize;

        printf("%f\n", finalAnswer);
    }
return 0;
}

And it works for most values, but pin 13 and 20 give the wrong answer. I looked through it several times, but I can’t understand what could be causing this.

Input number of X values:10 5.039070 Input number of X values:11 5.031651 Input number of X values:12 5.026160 Input number of X values:13 6.271982 Input number of X values:14 5.018732 Input number of X values:15 5.016153 Input number of X values:16 5.014071 Input number of X values:17 5.012367 Input number of X values:18 5.010955 Input number of X values:19 5.009773 Input number of X values:20 5.798243 Input number of X values:21 5.007917

+1
source share
3 answers

The problem is that in the condition for the output of the inner loop, you are comparing two floating point numbers. After numberOfStripsiterations, he did not guarantee that z == bdue to floating point precision. It is possible that z < bor z > b. In the case, the z < bcycle runs at a different time.

numberOfStrips :

float z = stripSize;
for (int i = 1; i < numberOfStrips; i++) {
    sumFirstAndLast += func(z);
    z += stripSize;
}
+2

float. float double.

, 6.271982 10 float, 5.021983 double.

, epsilon .

0

:

printf("%f, %d\n", z, z < b);

for z . :

1.000000, 1

, , . , 1.000 < 1.000. , , , (, numberOfXValues).

0
source

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


All Articles