0

I'm using Python 3 to use scipy's integrate.quad() function to integrate the expression (t^s / cosh^2(t)) for a given input s. I get the OverflowError: math range error.

My code looks like this:

from math import inf
from math import cosh
from scipy.integrate import quad
import numpy as np

def Integral_Expression(s):
    ans, err = quad(lambda t: (np.power(t,s))/(np.power(cosh(t),2)), 0, inf)
    return ans

I've seen other people who get the Math Range Error use numpy's exp() or power() methods to solve the problem, but it doesn't seem to be working. I also tried

and, err = decimal.Decimal(quad(lambda t: (power(t,s))/power(cosh(t),2), 0, inf))

with no success. Thanks for any help!

1
  • what range of s do you consider? Commented Jul 2, 2020 at 22:34

2 Answers 2

1

You could use Integration by substitution. Try to change variable to something that does not grow so rapidly like cosh(x).

Try:

t = log(u)

Now:

cosh(t) = 0.5 *  (exp(t) + exp(-t)) = 0.5 * (u + 1/u)
dt = du / u

After the change, the old integral

Integral[(t**s)/cosh(t)**2, 0, Inf]

becomes

Integral[log(u)**s/((u+1/u)/2)**2/u, 1, inf]

Note that integral boundaries had changed as well.

The result:

s = 2
quad(lambda u: (log(u)**s)/((u+1/u)/2)**2/u, 1, inf)

returns (0.8224670334241126, 1.1430967283843074e-11).

This solution is slightly more precise than approach based on replacing infinity with a large number:

>>> quad(lambda t: (t**s)/cosh(t)**2, 0, 100)
(0.8224670334241144, 1.3879318674935893e-08)
Sign up to request clarification or add additional context in comments.

Comments

0

There is a great chance that the problem comes from the square of cosh(t) that behaves like an exponential for t close to infinity. Maybe you can stop the upper bound of the integral to 100 given that 1/cosh(100)**2=5e-87 you are already reaching the floating point precision.

Note that you'll get the same error if you simply try to evaluate cosh(1000) in your python code:

print(cosh(1000))

Output:

% python3 script.py
Traceback (most recent call last):
  File "script.py", line 11, in <module>
    print(cosh(1000))
OverflowError: math range error

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.