Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does one of these code segment work while the other throws an overflow

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

like image 795
cobie Avatar asked Apr 12 '13 16:04

cobie


2 Answers

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.

like image 167
Martijn Pieters Avatar answered Sep 23 '22 23:09

Martijn Pieters


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.

like image 37
Josh Lee Avatar answered Sep 22 '22 23:09

Josh Lee