-5

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?

TsingHui
  • 49
  • 4
  • 1
    That is very, very odd. The output from C code should be `0.300000, 0.100000, 0.200000` _not_ `0.3 0.1 0.2`. Where are the commas? Where are 6 digits after dot? You are not executing the code you presented. The python code is also invalid, there should be no `...` in the output. Are you sure you have executed the code you presented? Please post the output from the commands you executed, not a different one. – KamilCuk Dec 31 '22 at 10:49
  • `Is there any way to improve Python?` Please define "improve". Improve in what way, _exactly_? – KamilCuk Dec 31 '22 at 10:54
  • Change your C `printf` formats to use `%.20lf`, and then see [Is floating point math broken?](https://stackoverflow.com/questions/588004) – Steve Summit Dec 31 '22 at 13:48

2 Answers2

3

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/ .

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
1

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

0___________
  • 60,014
  • 4
  • 34
  • 74