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
(Do you need help getting the interactive interpreter running? If so,
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)
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:
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
# 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:
although the website doesn’t mention that it just cuts the calculation
This topic of floating point maths gets pretty complicated, but you
can read about the basics of it in the Python FAQs and tutorial:
Here are a couple of other excellent discussions:
Good luck and feel free to ask any more questions if anything is