Lars Nordin
Lars Nordin

Reputation: 2828

python - why does multiplication of long and float produce decimal-like answer?

In this example:

long_ten = 10**21
print('  type(long_ten):', type(long_ten))
print('     long_ten: {:52,f}'.format(long_ten))
tenth = 0.1
print('  type(tenth):', type(tenth))
print('   float(52f): {:52.52f}'.format(tenth))
float_res = tenth * long_ten
print('\n  type(float_res):', type(float_res))
print(' float(52f): {:15.52f}'.format(float_res))

Why does multiplying a long and float result in a float with decimal-like precision?

type(long_ten): <type 'long'>
long_ten:                 1,000,000,000,000,000,000,000.000000
type(tenth): <type 'float'>
float(52f): 0.1000000000000000055511151231257827021181583404541016

type(float_res): <type 'float'>
float(52f): 100000000000000000000.0000000000000000000000000000000000000000000000000000

I would expect the result to be:

100000000000000005551.1151231257827021181583404541016...

I understand why the result type is float - b/c it is wider than long

NOTE - this is using python 2 (if that matters)

Upvotes: 0

Views: 592

Answers (2)

Stefan Pochmann
Stefan Pochmann

Reputation: 28656

100000000000000000000 is representable as float:

>>> n = 100000000000000000000
>>> int(float(n))
100000000000000000000L

The next larger float is 100000000000000016384:

>>> from itertools import count
>>> next(int(float(i)) for i in count(n) if int(float(i)) != n)
100000000000000016384L

Thus the float closest to your expected 100000000000000005551.115... is 100000000000000000000, so that's what you get.

Why are floats this large always integers? Well, you can see in binary it's already 67 bits:

>>> bin(n)
'0b1010110101111000111010111100010110101100011000100000000000000000000'
>>> len(bin(n)[2:])
67

But floats only store the most significant 53 bits. So since the front bit is worth 266, the tail bit is already worth 266-52 = 16384. As we've already seen above. So all 53 bits are worth integers and thus the whole number is an integer as well.

Upvotes: 2

Davis Herring
Davis Herring

Reputation: 40043

Floating-point numbers are just a certain set of fractions whose denominators are powers of 2. 2^-n has n digits after the decimal, so a float can easily have 53 non-zero digits (more for large numbers, since no power of 2 is a power of 10). You're just printing (nearly) that "full" number; we usually don't do that, since all but the first 16 (or so) are just "noise" determined by those first few.

Upvotes: 0

Related Questions