Floating-point numbers

The result of 12+12.23 is 35.120000000000005
The result of 23+12.23 is 35.230000000000004
And the result of 1.2-1 is 0.19999999999999996
But in C++ the results are true.
Why?What is the difference between C++ and Python at floating-point numbers
Note:
The result of 0.1+0.1 is 0.2
It is true.But the result of 1.2-1 is false

Some language runtimes round floats and doubles.

Decimal numbers sometimes do not have a precise representation in binary math - and floats and doubles are binary math.

If you need precisely-represented decimal values (EG, for an accounting application), use decimal math like the decimal.Decimal class:

Note in both languages the actual numerical result should be exactly the same - Python floats are going to be identical to C doubles. The difference is how the language is choosing to convert them to strings to display them. Notice how if you rounded Python’s result to say 10 decimal places, it’d be exactly correct. If you modify your C program to specify a lot of decimals (20, say), it should produce the same inprecision in the end.

The core problem here is that the numbers are stored in binary, not decimal, which means different numbers can be represented exactly. In decimal math, 1/3 can’t be written exactly - 0.3333 is close but not perfect, while 1/4 = 0.25 exactly. In binary math, it’s a different set of fractions which can be handled exactly - in particular ⅒ cannot be represented perfectly, so you end up with this very slight difference. In practice it’s really not a big deal, because the important first decimal points are all exact.

1 Like

I wonder if perhaps the OP was using a float in C, but untagged literals, which are of type double?

float x = 0.1 + 0.2;

This will do double-precision arithmetic, but then downcast to float. Even if 0.1 is put into a float, and then 0.2 is added afterwards, the float would most likely be upcast to double, then the arithmetic done, and then the result is downcast back to float.

No it isn’t.

>>> 12 + 12.23
24.23

Perhaps you mean:

>>> 12 + 23.12
35.120000000000005

Why is this not the same as you expect from school? Because floating point maths on the computer does not, and can not, use mathematical exact real numbers. Floats are limited to 64 bits of binary digits, which is approximately 16-17 decimal digits.

See the FAQs and the tutorial.

All programming languages, including C++, suffer from this same issue. But some programming languages try to hide the fact by lying to you. For example, the R interpreter only shows a few decimal places, so that numbers which are different look the same:

> c(0.199999999, 0.2, 0.20000001)
[1] 0.2 0.2 0.2

I discovered this when I had a program calculate five numbers, which looked identical in the R interpreter, but weren’t:

> fn
[1] 0.2 0.2 0.2 0.2 0.2
> fn == 0.2
[1]  TRUE TRUE FALSE FALSE FALSE

Python will never lie to you like this but other languages might.