Skip to content Skip to sidebar Skip to footer

RuntimeWarning: Overflow Encountered In Cosh -- Python. What Does This Mean?

I'm running the following calculation: N = 2**15 dx = 0.1 x = np.arange(-N/2,N/2) u0 = np.zeros([N, 1]) L = N * dx x0 = x[1] + 2 * delta delta = 15 while x0 < L - delta: l

Solution 1:

cosh grows very large:

In [70]: np.cosh(2**10)
<ipython-input-70-c4511154ec1e>:1: RuntimeWarning: overflow encountered in cosh
  np.cosh(2**10)
Out[70]: inf

Why is your x so wide? For most of the range, the inverse of this cosh will be 0.

In [72]: N=2**15; x = np.arange(-N/2,N/2)
In [73]: len(x)
Out[73]: 32768
In [74]: r = 1/(np.cosh(x)**2)
<ipython-input-74-404fbe3be390>:1: RuntimeWarning: overflow encountered in cosh
  r = 1/(np.cosh(x)**2)
<ipython-input-74-404fbe3be390>:1: RuntimeWarning: overflow encountered in square
  r = 1/(np.cosh(x)**2)
In [75]: r[:10]
Out[75]: array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

In [77]: np.sum(r<1e-16)
Out[77]: 32729

Look at a +-20 range for x

In [88]: x = np.arange(-20,20)
In [89]: r = 1/(np.cosh(x)**2)
In [90]: r
Out[90]: 
array([1.69934170e-17, 1.25565312e-16, 9.27809132e-16, 6.85563373e-15,
       5.06566622e-14, 3.74304919e-13, 2.76576004e-12, 2.04363561e-11,
      ...
       1.00000000e+00, 4.19974342e-01, 7.06508249e-02, 9.86603717e-03,
       ...
       1.51005382e-10, 2.04363561e-11, 2.76576004e-12, 3.74304919e-13,
       5.06566622e-14, 6.85563373e-15, 9.27809132e-16, 1.25565312e-16])

suppressing the warnings

In [148]: x=np.array([-2**15,-2**4,0,2**4,2**15])

In [155]: np.cosh(x)
<ipython-input-155-1e743139b88e>:1: RuntimeWarning: overflow encountered in cosh
  np.cosh(x)
Out[155]: 
array([           inf, 4.44305526e+06, 1.00000000e+00, 4.44305526e+06,
                  inf])
In [156]: 1/(np.cosh(x)**2)
<ipython-input-156-5cf76600c0c7>:1: RuntimeWarning: overflow encountered in cosh
  1/(np.cosh(x)**2)
Out[156]: 
array([0.00000000e+00, 5.06566622e-14, 1.00000000e+00, 5.06566622e-14,
       0.00000000e+00])

The warning does not prevent you from getting useful values. It is a warning, not an error.

But can suppress the warning. On way is with errstate:

In [157]: with np.errstate(over='ignore'):
     ...:     y = 1/(np.cosh(x)**2)
     ...: 
In [158]: y
Out[158]: 
array([0.00000000e+00, 5.06566622e-14, 1.00000000e+00, 5.06566622e-14,
       0.00000000e+00])

np.seterr can also be used, but it will change handling for the whole script, not just this context. So the with np.errstate is preferred.

Do take time to read the docs.

In [159]: np.geterr()
Out[159]: {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}

There is also a warnings module

Why can't I suppress numpy warnings


Post a Comment for "RuntimeWarning: Overflow Encountered In Cosh -- Python. What Does This Mean?"