Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python why is 10e26 != 10**26 ? (Floating point inaccuracy?)

I was trying to process some rather large numbers in python and came across an overflow error. I decided to investigate a little bit more and came across an inequality I cannot explain. When I evaluate 10^26 I get:

>>> 10**26
100000000000000000000000000

Which is perfectly logical. However when I evaluate 10e26 and convert it to an int I get:

>>>int(10e26)
1000000000000000013287555072

Why is this? Do I not understand the e notation properly? (From what I know 10e26 is 10*10^26 as seen in this answer: 10e notation used with variables?)

10^26 is way past the max integer size so I was also wondering if there was any mechanism in python which could allow to work with numbers in scientific format (not considering all those zeros) in order to be able to compute operations with numbers past the max size.

like image 323
A.D Avatar asked Feb 11 '26 06:02

A.D


2 Answers

The short answer is that 10e26 and 10**26 do not represent identical values.

10**26, with both operands being int values, evaluates to an int. As int represents integers with arbitrary precision, its value is exactly 1026 as intended.

10e26, on the other hand, is a float literal, and as such the resulting value is subject to the limited precision of the float type on your machine. The result of int(10e26) is the integer value of the float closest to the real number 1027.

like image 74
chepner Avatar answered Feb 18 '26 07:02

chepner


10e26 represents ten times ten to the power of 26, which is 1027.

10**26 represents represents ten to the power of 26, 1026.

Obviously, these are different, so 10e26 == 10**26 is false.

However, if we correct the mistake so we compare 1e26 and 10**26 by evaluating 1e26 == 10**26, we get false for a different reason:

  • 1e26 is evaluated in a limited-precision floating-point format, producing 100000000000000004764729344 in most implementations. (Python is not strict about the floating-point format.) 100000000000000004764729344 is the closest one can get to 1026 using 53 significant bits.
  • 10**26 is evaluated with integer arithmetic, producing 100000000000000000000000000.
  • Comparing them reports they are different.

(I am uncertain of Python semantics, but I presume it converts the floating-point value to an extended-precision integer for the comparison. If we instead convert the integer to floating-point, with float(10**26) == 1e26, the conversion of 100000000000000000000000000 to float produces the same value, 100000000000000004764729344, and the comparison returns true.)

like image 26
Eric Postpischil Avatar answered Feb 18 '26 08:02

Eric Postpischil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!