Home > Mobile >  Different floating-point calculations between Python and c
Different floating-point calculations between Python and c

Time:12-31

Subtraction of floating point numbers in python and c doesn't behave the same, when I try "0.3 - 0.1", c tells me 0.2 and python tells me 0.199999...98.

I wrote the following c code:


// a.c

#include <stdio.h>

#include <stdlib.h>

int main(int argc, char **argv)

{

  double a, b;

  a = strtod(argv[1], NULL);

  b = strtod(argv[2], NULL);

  printf("%lf, %lf, %lf\n", a, b, a - b);

  return 0;

}

and i calculate 0.3 - 0.1


> gcc a.c -O3

> ./a.out 0.3 0.1

  0.300000 0.100000 0.200000

looks good so far.

but when i calculate in python:


# idle

>>> 0.3 - 0.1

0.19999999999999998

why? Why do the two behave differently. Is there any way to improve Python? Or the authors of Python have tried their best?

CodePudding user response:

why? Why do the two behave differently

Because printing a floating-point number in C using printf with %lf format specifier prints the number with precision of 6 digits after the decimal point, while in python the number is printed using "precision high as needed to represent the actual value". See https://docs.python.org/3.7/library/string.html#formatspec and https://en.cppreference.com/w/cpp/io/c/fprintf and Printf width specifier to maintain precision of floating-point value .

Is there any way to improve Python?

If by the word "improve" you mean to get the same output from python as in C code, you would format it properly. To get the same output as your C code should have outputted, you can:

>>> print("{:f}, {:f}, {:f}".format(0.3, 0.1, 0.3 - 0.1))
0.300000, 0.100000, 0.200000

the authors of Python have tried their best?

I will strongly assume that they did. They are giving an amazing project for free, which is amazing. Consider supporting them, see https://www.python.org/about/help/ .

CodePudding user response:

There is no difference. Print more digits in C and you will see that printf has simply rounded the values.

  printf("%.20f, %.20f, %.20f\n", a, b, a - b);

https://godbolt.org/z/Mf5cr96d4

  • Related