0

I'm new to Python and I'm having trouble with this:

import cmath as cm
import numpy as np
from scipy import special
from scipy.misc import derivative
def T(X, Y):
    s0 = np.sign(X)
    s1 = np.sign(X - 15)
    s3 = np.sign(X + 15)
    k0 = cm.sqrt( X**2 -(10*Y)**2 )/10
    k1 = cm.sqrt( ((X - 15)**2) - (10*Y)**2 )/10
    k3 = cm.sqrt( ((X + 15)**2) - (10*Y)**2 )/10
    def z(k):
        return complex(k, -Y)/cm.sqrt(k**2 + Y**2)
    def w(k, s, x):
        return np.array([[cm.exp(complex(0, 1)*k*x), cm.exp(-complex(0, 1)*k*x)], [s*z(k)*cm.exp(complex(0, 1)*k*x), -s*cm.exp(-complex(0, 1)*z(k)*x)/z(k)]])
    I15 = np.linalg.inv(w(k1, s1, 5))
    I05 = np.linalg.inv(w(k0, s0, 5))
    I310 = np.linalg.inv(w(k3, s3, 10))
    Omega = w(k1, s1, 0).dot(I15).dot(w(k0, s0, 5)).dot(I05).dot(w(k3, s3, 5)).dot(I310)
    Omegan = special.eval_chebyu(19, np.trace(Omega)/2)*Omega - special.eval_chebyu(18, np.trace(Omega)/2)*np.identity(2)
    I00 = np.linalg.inv(w(k0, s0, 0))
    tt = I00.dot(Omegan).dot(w(k0, s0, 200))
    t = 1/tt[0][0]
    return cm.log(t)
def V(X):
    Y0 = X*np.sin(np.deg2rad(2))/10
    result = derivative(func=T, x0=Y0, args=(X,))*X/(20*np.pi)
    return -result.imag
V = np.vectorize(V)
X = np.linspace(0.01, 10, 1000)
VX = V(X)

I'm getting an OverflowError: math range error, when trying to run this code. Is there a way to avoid this error? Any help is appreciated. Thanks!

ABDOU
  • 1

1 Answers1

1

How to debug:

  1. Change your function w like this:
def w(k, s, x):
    try:
        return np.array([[cm.exp(complex(0, 1)*k*x), cm.exp(-complex(0, 1)*k*x)], [s*z(k)*cm.exp(complex(0, 1)*k*x), -s*cm.exp(-complex(0, 1)*z(k)*x)/z(k)]])
    except OverflowError:
        import pdb
        pdb.set_trace()
  1. Run your program:
#> python myprog.py
--Return--
> /Users/xxx/tmp/myprog.py(19)w()->None
-> pdb.set_trace()
(Pdb)
  1. Debug by testing all your expressions:
(Pdb) locals()
{'k': 3.5499997838094535j, 's': 1.0, 'x': 200, 'z': <function T.<locals>.z at 0x124770c10>, '__return__': None}

(Pdb) cm.exp(complex(0, 1)*k*x)
(4.47647977601281e-309+0j)

(Pdb) cm.exp(-complex(0, 1)*k*x)  # The problem is here x=200, x=199 works
*** OverflowError: math range error
Dharman
  • 30,962
  • 25
  • 85
  • 135
Corralien
  • 109,409
  • 8
  • 28
  • 52
  • but, how to avoid the error? what should I modify in my code. – ABDOU Aug 24 '21 at 23:19
  • Try to deal with [`bigfloat`](https://bigfloat.readthedocs.io/en/latest/) package. Check this answer: https://stackoverflow.com/a/4050933/15239951 to understand the error. – Corralien Aug 24 '21 at 23:34