Python math range error

Coder117 picture Coder117 · Mar 31, 2017 · Viewed 10.9k times · Source

I'm getting an error when trying to calculate a very large number in Python. Here is my code:

# Where fourthNumber = 2790
# and dee = 413
emm = math.pow(fourthNumber, dee)

An my error is:

line 44, in <module>
    emm = math.pow(fourthNumber, dee)
OverflowError: math range error

Is there a way around this error? I thought Python could handle arbitrarily large numbers? Or am I wrong? Any help is appreciated. Thanks!

Answer

Willem Van Onsem picture Willem Van Onsem · Mar 31, 2017

The problem is that math.pow(..) works on floating point numbers. In Python floating point numbers are not arbitrary large. Only ints are (in , and longs in ).

You can however use the ** operator which does integer power (given of course the arguments are integers) if the two numbers are integers:

>>> 2790**413
10827693458027068918752254513689369927451498632867702850871449492721716762882046359646654407147290095143376244612860740505063304616869045757879636651922242895944635094287526023557872050108996014618928707382416906723717536207944990935946477343103732942220495426003253324856391048675505527041527544249845903325107575822015010197006079682477544271998209608154757421132764034059289159228295810448568286783859864141487725512980856505994152145510660350938086763233208252511256291934375881870590480237727775536326670654123168787472077359939510018827829233028430183558108518520524567765780717109616748933630364200317687291046055118737587697510939517252245710306646155772831436013971724481443654932630319085588147436112198934867224850036968074130558127066188475740553149587714112808551835880666012903651859580234129805580074844684526620091506655345299434455806896837926335229779632528684030400890708579038639280240022309690038032176604539091205540422068492362106868171343650410145963283813864374487990607671475570427243900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

If you however cast it to a float, you get:

>>> float(2790**413)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: int too large to convert to float

So the error clearly shows that cannot handle this large numbers as floats.