Python Forum

Full Version: standard data types
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I just started to learn Python a bit. At the moment I am busy to get familiar with the standard data types. It looks pretty easy that there is only one int data type. Doesn matter the value you want to store. I made a very simple application, initialize a variable with a big value. For example with the value 120000000000000000001. Multiply this value by 3, store it in a the same or in an other variable. Then divide it by 3. The result is not the same as the start value. See code below.

startValue = 120000000000000000001
result_1 = (3 * startValue)
result_2 = int(result_1 / 3)
print(startValue)
print(result_1)
print(result_2)

Is in the above example a variabele or internal result saved as a floating point? Why is result_2 not equal to the startValue? Can this be solved? If so, how.
Division (at least in Python 3.0+) returns a floating point number. Since the number you gave it is so large, it loses some precision when converted to floating point. If you want to force an integer result without the sidestep into floating point, you can do so with integer division (result_1 // 3).
In fact int(float(startValue)) is not equal to startValue. StartValue needs 67 bits to be stored
>>> int(float(startValue))
120000000000000000000
>>> startValue.bit_length()
67
Floating numbers are stored on 64 bits from which only 53 are used for precision. A little bit of precision is lost in the conversion.
Thanks Ichabod! Indeed this is the solution