Python3 ex5 related question

Hi,
I am new to programming. Why are these codes output have different values? I already search and cannot find the related explain or may be I cannot understand their meanings.

Code = Result
print(1 + 2) = 3
print(1 + 2.2) = 3.1
print(1.1 + 2.2) = 3.3000000000000003

Thanks,
atr

Hmmm that’s odd. I can not replicate the second result as mine calculates correctly as a float.

The third result is really odd. I know you get odd results with integer division but I’ve not seen this before with addition. Following thread for insight. Perhaps @zedshaw can enlighten us…

def add(a,b):
    return a + b
    
print(add(1, 2))
print(add(1, 2.2))
print(add(1.1, 2.2))

Results:

3
3.2
3.3000000000000003
Execution completed in 5ms.
1 Like

Aha!!! Found this: https://docs.python.org/3/tutorial/floatingpoint.html

2 Likes

So that’s correct but the final one is probably surprising. Honestly that’s just because computer suck at floating point math by default. If you want very accurate floating point then you use:

https://docs.python.org/3/library/decimal.html

1 Like