Python Forum

Full Version: python calculate float plus float is incorrect?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi everybody

maybe , try print(27.56+13.78)

I use 3.10.12 and 3.12, get result is 41.339999999999996.
what happend?
It is all explained here. Also it has nothing to do with Python. It's due to the internal representation of floating point numbers by computers. The same issue exists in other programming languages.
but, i use php to calcu, the result is correct 41.34

<?php
$a=27.56;
$b=13.78;
echo $a+$b;
?>

41.34
I don't know PHP, but here is a warning about the same thing in PHP. I don't know why it displays 41.34 in your case (perhaps an effect of the echo command?). Try their example perhaps
Output:
floor((0.1+0.7)*10)
a = 27.56
b = 13.78
c = a + b
print(f"{c:.2f}")
Output:
41.34
ok, thank all, i understand.
I don't know what PHP does to prevent the visible inaccuracy.
In modern programming languages, you don't see the real floating point value inclusive PHP.

An algorithm is used, to show the user a nicer representation of the floating point value.
But this does not always work (e.G. 0.2 + 0.1).

Ancient programming languages haven't used it, so the user was able to see the imprecision caused
by the conversion from 10base to binary.

The key point is, that you can't represent all decimal numbers as binary numbers.

But there are different solutions.
# slow, but precise
from decimal import Decimal

# the quotes are mandatory
# if you use float literals, it's already imprecise before Decimal is instantiated
a = Decimal("27.56")
b = Decimal("13.78")
print("Decimal:", a + b)
# Scientific rounding

a = 27.56
b = 13.78
print("Round 2 decimal places:", round(a + b, 2))
# floor
# ceil

from math import ceil, floor

a = 27.56
b = 13.78
print("floor:", floor(a+b))
print("ceil:", ceil(a+b))
# adding the two int => int
# then divide by 100 => float

a = 2756
b = 1378

print("Int addition", (a+b) / 100)
# not rounding, just formatting the output instead of changing the float itself

a = 27.56
b = 13.78

c = a + b

print(f"Output formatting: {c:.2f}")
Output:
Decimal: 41.34 Round 2 decimal places: 41.34 floor: 41 ceil: 42 Int addition 41.34 Output formatting: 41.34