8

I am working with python and I am trying to find powers of really large numbers but something interesting which happens is that this throws a math overflow

math.pow(1000, 1000)

but this below seems to work although I do not know if the value returned is correct

1000**1000

Anybody aware why this happens

cobie
  • 7,023
  • 11
  • 38
  • 60

2 Answers2

8

Simple, the math.pow() method uses C float libraries, while the ** power operator uses integer maths.

The two methods have different limitations. Python int size is only limited by how much memory your OS will let Python have, float numbers are limited by your computer architecture, see sys.float_info.max.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
7

math.pow:

Unlike the built-in ** operator, math.pow() converts both its arguments to type float. Use ** or the built-in pow() function for computing exact integer powers.

Josh Lee
  • 171,072
  • 38
  • 269
  • 275
  • any idea on the limits beyond which we cannot assume that the value returned is correct for any of these? – cobie Apr 12 '13 at 17:03
  • Also, because math.pow returns float result, and 1000^1000 will not fit not float anyhow – Alex Turbin Apr 12 '13 at 17:04
  • @cobie Integer math is always correct. Floating point math is correct up to rounding error, or until you hit the maximum value of `sys.float_info.max`. – Josh Lee Apr 12 '13 at 17:08