Large number in python gives infinity

67 Views Asked by At

I dealing with data with very large numbers this error appears for example if I am trying to calculate for example:

import random
import numpy as np
import cmath
import math
import mpmath
from scipy.special import gamma, factorial
A= 11.6 ** 422.5

RuntimeWarning: overflow encountered in double_scalars

the output is inf

I tried to use

A= np.float128(11.6 ** 422.5)

to store the number but is said that id does not work fo windows

can any body please provide a solution store this value instead of giving inf

2

There are 2 best solutions below

2
Daweo On

You might use decimal.Decimal for that purpose

import decimal
result = decimal.Decimal("11.6") ** decimal.Decimal("422.5")
print(result)

gives output

5.413778068101126642433515669E+449

decimal is part of standard library.

0
hpaulj On

This produces a python float error:

In [28]: 11.6 ** 422.5
---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
Cell In[28], line 1
----> 1 11.6 ** 422.5

OverflowError: (34, 'Result too large')

In [29]: np.array(11.6) ** 422.5

Using numpy: C:\Users\14256\AppData\Local\Temp\ipykernel_6764\1884378001.py:1: RuntimeWarning: overflow encountered in power np.array(11.6) ** 422.5 Out[29]: inf

numpy, at least on windows, does not have larger floats:

In [30]: np.array(11.6).astype('float128')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[30], line 1
----> 1 np.array(11.6).astype('float128')

TypeError: data type 'float128' not understood

But since you are import mpmath, you can use that:

In [32]: mpmath.mpf(11.6) ** 422.5
Out[32]: mpf('5.4137780681010568e+449')