precision of trapezoidal rule in Python and C

The difference is because even though double v[200] = {}; has double precision, float area = 0.0; is a floating-point number, so half the precision is lost.

Python will use double by default and thus keep the precision.


As you can see, floating-point numbers quickly lose precision:

#include <stdio.h>

int main()
{
    float pi_flt = ((float)22)/7;
    double pi_dbl = ((double)22)/7;

    printf("%.8f, %.8lf\n", pi_flt, pi_dbl);
    return 0;
}

Compile and run:

$ clang -Weverything test.c
test.c:9:29: warning: implicit conversion increases floating-point precision: 'float'
      to 'double' [-Wdouble-promotion]
    printf("%.8f, %.8lf\n", pi_flt, pi_dbl);
    ~~~~~~                  ^~~~~~
1 warning generated.
$ ./a.out
3.14285707, 3.14285714

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top