I’m trying to understand what is happening in the python code below. I take the square root of 2 and divide its decimals by 1. Doing this for 5 times keeps giving the same value but the 6th and 7th time I get different values.
Why does the output change at the 6th time when the input value is the same as in the previous 5 calculations?
import math as M
frct = M.sqrt(2)
# 1
frct = 1 / (frct - int(frct))
print frct # 2.41421356237
# 2
frct = 1 / (frct - int(frct))
print frct # 2.41421356237
# 3
frct = 1 / (frct - int(frct))
print frct # 2.41421356237
# 4
frct = 1 / (frct - int(frct))
print frct # 2.41421356237
# 5
frct = 1 / (frct - int(frct))
print frct # 2.41421356237
# 6
frct = 1 / (frct - int(frct))
print frct # 2.41421356238
# 7
frct = 1 / (frct - int(frct))
print frct # 2.41421356235
Short version, Python is rounding the output 🙂
Long version, floating points don’t store the real (no pun intended) value, they store an exponent and mantissa. See this wikipedia page for more info: http://en.wikipedia.org/wiki/Floating_point
Basically, a floating point number is stored like this:
If you want a more precise version in Python, try the decimal module:
Output: