Hi Roger,
If that code you give is actually your script, the result you would get
will be a syntax error:
SyntaxError: 'return' outside function
But putting that aside, you say:
“when i run this script and enter 12.2 as num1 and multiply num1 with 3
as num2 i get 36.599999999999994 We all know it should be 36.6.”
We don’t need a script to test this. We can use Python as a calculator.
In the interpreter, at the >>>
prompt, just type in the calculation
you want:
>>> 12.2*3
36.599999999999994
(Do you need help getting the interactive interpreter running? If so,
please ask.)
What’s going on here?
The trick to understand is that even though we enter 12.2, what the
computer actually sees is:
>>> print('%.60f' % 12.2)
12.199999999999999289457264239899814128875732421875000000000000
and when you multiply that by 3, you get 36.599999999999994.
And the reason for that weird 12.1999… is that the base ten number
12.2 cannot be calculated exactly in base two, and computers use base
two for numbers.
You might remember calculating 1/3 as a decimal back in primary school
when you learned how to do division, and getting:
0.3333333...
where the threes go on and on forever. 12.2 in binary is like that, the
true value goes on and on forever. Obviously no computer has an infinite
amount of memory, so Python floats are limited to 64-bits and the exact
binary number
# base 2
1100.0011001100110011001100110011... # goes on forever
gets chopped off after approximately 50 bits past the dot (binary
point). And that number is just a tiny bit smaller than the exact
value 12.2 (decimal): our unexpected 12.19999… number above.
You might like to play around with base conversions here:
https://binary2hex.com/numberconverter.html?id=84142
although the website doesn’t mention that it just cuts the calculation
off early.
This topic of floating point maths gets pretty complicated, but you
can read about the basics of it in the Python FAQs and tutorial:
https://docs.python.org/3/faq/design.html#why-am-i-getting-strange-results-with-simple-arithmetic-operations
https://docs.python.org/3/tutorial/floatingpoint.html#tut-fp-issues
Here are a couple of other excellent discussions:
https://fabiensanglard.net/floating_point_visually_explained/
https://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/
Good luck and feel free to ask any more questions if anything is
unclear.