RuntimeWarning: invalid value encountered in arccos - python

I am new to using Python but getting along with it fairly well. I keep getting the error you see below and not sure what the problem is exactly as I believe the values are correct and stated. What do you think the problem exactly is? I am trying to graph from t = 0 to t=PM, and the formula you see below is angle arccos.
Couldn't find the troubleshooting of this arccos error online. Running Python 3.5.
import numpy as np
import matplotlib
from matplotlib import pyplot
from __future__ import division
rE = 1.50*(10**11)
rM = 3.84*(10**8)
PE = 3.16*(10**7)
PM = 2.36*(10**6)
t = np.linspace(0, PM, 200)
# anaconda/lib/python3.5/site-packages/ipykernel/__main__.py:1: RuntimeWarning: invalid value encountered in arccos
y = 0.5*(np.arccos(2*(np.pi)*t*((1/PM)-(1/PE))+90))

If you simplify to just
np.arccos(90)
(which is the first element in the array being passed to arccos), you'll get the same warning
Why is that? arccos() attempts to solve x for which cos(x) = 90. However, such a value doesn't make sense as it's outside of the possible domain for arccos [-1,1]
Also note that at least in recent versions of numpy, this calculation returns nan
>>> import numpy as np
>>> b = np.arccos(90)
__main__:1: RuntimeWarning: invalid value encountered in arccos
>>> b
nan

The np.arccos() function can only take values between -1 and 1, inclusive.
See: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.arccos.html

Related

How to vectorize a function in python that includes a limit (e.g. sin(x)/x)

I have a complex function that includes (sin(x)/x). At x=0, this function has a limit of 1, but when numerically evaluated is NaN.
This function is vectorized to get high performance when evaluating a large number of values, but fails when x=0.
A simplified version of this problem is shown below.
import numpy as np
def f(x):
return np.sin(x)/x
x = np.arange(-5,6)
y = f(x)
print(y)
When executed, this returns:
... RuntimeWarning: invalid value encountered in true_divide
return np.sin(x)/x
[-0.19178485 -0.18920062 0.04704 0.45464871 0.84147098 nan
0.84147098 0.45464871 0.04704 -0.18920062 -0.19178485]
This can be addressed by trapping the error, finding nan and substituting for the limit.
Is there a better way to handle a function like this?
Note: The function is more complex than sin(x)/x. The limit is know. Theuse of sinc is not an option. sin(x)/s is used to illustrate the problem.
You could try to use true_divide with where to specify the place where you want to divide and out to pass in an out array that contains the result you expect at the places were you don't want to divide. Not sure if this is the most optimal solution but that would work. In code that should read liad
res = np.true_divide(sin(x), x, where=x!=0, out=np.ones_like(x))
I'm used to this option while I'm doing my plots:
x = np.arange(-5, 6, dtype=float)
domain = x!=0
fill_with = np.nan
f = np.divide(np.sin(x), x, out=np.full_like(x, fill_with), where=domain)
You can customize any domain and value to fill with outside the domain.
there's an implementation of numpy sinc that you can use.

Why am I getting the error: 'Mul' object has no attribute 'exp'?

I am trying desperately to be able to integrate a matrix and this is my 3rd or 4th approach. Every time I try to resolve an error, I get a new one and get stuck. This time, I am getting the error:
---------------------------------------------------------------------------
PolynomialError Traceback (most recent call last)
<ipython-input-20-445ad8aa95c1> in <module>
25 var = 0.16
26 A = (1/var)*transpose#M
---> 27 A.integrate((s,0,1))
PolynomialError: 1.0*(6.25000000000002*_t0 + 0.0359195402298851)/(1.0*_t0 + 0.00574712643678161) is not an element of K[_t0, 1/_t0].
I have looked at every other post with regards to this error (including the one about cosine) and nothing resolves my error. I have tried np.exp, sym.exp, etc.
import sympy
from scipy.integrate import odeint
%matplotlib inline
import matplotlib.pyplot as plt
import scipy.integrate as integrate
from scipy.linalg import inv
from sympy.matrices import Matrix
from sympy.abc import s
from sympy import symbols, diff, exp, log, power
#M = Matrix([[x, y], [1, 0]])
#M.integrate((x, ))
K = 17.5
r = 0.7
x0 = 0.1
dxdK = (x0*x0-x0*x0*sympy.exp(-r*s))/((x0+K*sympy.exp(-r*s)-x0*sympy.exp(-r*s))**2)
dxdr = (K*K*x0*s*sympy.exp(-r*s)-K*x0*x0*s*sympy.exp(-r*s))/((x0+K*sympy.exp(-r*s)-x0*sympy.exp(-r*s))**2)
dxdx0 = (K*x0+K*K*sympy.exp(-r*s)-K*x0*sympy.exp(-r*s)-K*x0+K*x0*sympy.exp(-r*s))/((x0+K*sympy.exp(-r*s)-x0*sympy.exp(-r*s))**2)
M = Matrix([[dxdK, dxdr, dxdx0]])
transpose = M.T
var = 0.16
A = (1/var)*transpose#M
A.integrate((s,0,1))
As stated before, my only real goal is to be able to integrate the matrix (1/var)*tranpose#M with respect to s. I'm currently trying to resolve the error above, but am also open to suggestions to changing the code entirely to just be able to integrate the thing (which is why I provided so much of the code). I have another post with previous code I had to try and integrate it, but never got a good answer.

sklearn adjusted mutual information score breaks on large set

from sklearn.metrics import adjusted_mutual_info_score
import numpy as np
a = np.random.randint(0,2,30000000)
b = np.random.randint(0,2,30000000)
print(a.shape)
print(b.shape)
c = adjusted_mutual_info_score(a,b)
print(c)
If you run the following code, you will get out:
RuntimeWarning: invalid value encountered in log
log_outer = -np.log(outer) + log(pi.sum()) + log(pj.sum())
nan
I don't understand why is that, but if you make a smaller sets of 1000 values, everything runs perfectly. Could anyone explain to me what is happening and how to fix this? I would appreciate it.

Numerical integration with scipy.integrate.trapz returns a result but scipy.integrate.simps does not

I am trying to integrate the following data numerically:
t,y
9.960000000000001e-05,8.334379999999999e-05
9.98e-05,0.000126125
0.0001,0.00018125
0.0001002,0.0002385
0.00010040000000000001,0.000289625
0.0001006,0.000347313
0.0001008,0.000391719
0.000101,0.00043284399999999994
0.00010120000000000001,0.000472375
0.00010140000000000001,0.000502469
0.00010160000000000002,0.000528594
0.00010180000000000001,0.000546219
0.000102,0.000569188
0.0001022,0.000584719
0.0001024,0.000593969
0.00010260000000000001,0.000607375
0.0001028,0.000618906
0.000103,0.000629344
0.0001032,0.000629344
0.0001034,0.000636313
0.00010360000000000001,0.0006374999999999999
0.0001038,0.000630375
0.00010400000000000001,0.00059875
0.0001042,0.00046825
0.0001044,0.000287344
0.00010460000000000002,0.000208594
0.0001048,0.000196094
0.000105,0.000172625
0.00010520000000000001,0.000134781
0.0001054,0.000115906
0.0001056,0.00010306300000000001
0.00010580000000000001,9.31563e-05
As shown below, I read this data set from a csv file.
This is my code:
import pandas as pd
from scipy.integrate import trapz, simps
root="my/root/dir"
df = pd.read_csv(root+r"simps.csv")
print(trapz(df["t"], df["y"]))
print(simps(df["t"], df["y"]))
trapz returns a value (-9.5865055e-10) while simps returns nan and the following error:
anaconda\path\scipy\integrate\quadrature.py:324: RuntimeWarning: divide by zero encountered in true_divide
h0divh1 = h0 / h1
anaconda\path\scipy\integrate\quadrature.py:326: RuntimeWarning: divide by zero encountered in true_divide
y[slice1]*hsum*hsum/hprod +
anaconda\path\scipy\integrate\quadrature.py:327: RuntimeWarning: invalid value encountered in add
y[slice2]*(2-h0divh1))
anaconda\path\scipy\integrate\quadrature.py:326: RuntimeWarning: invalid value encountered in add
y[slice1]*hsum*hsum/hprod +
Why does this error occur?
A very stupid mistake: I exchanged x and y. Simps requires y as a first argument

"RuntimeWarning: invalid value encountered in power" Using Scipy's ODR

I'm attempting to fit a function using Scipy's Orthogonal distance regression (odr) package and I keep getting the following error:
"RuntimeWarning: invalid value encountered in power"
this happened when I would use scipy's curve_fit function but I could always safely ignore the warning. But now it seems this is causing a numerical error that halts the fitting. I have based my code off of the example I found here:
python scipy.odrpack.odr example (with sample input / output)?
Here is my code:
import numpy as np
import scipy.odr.odrpack as odrpack
def divergence(x,xDiv):
return ( 1 - (x/xDiv) )**( -2.4 )
xValues = np.linspace(.25,.37,12)
yValues = np.array([ 6.94970607, 9.12475506, 10.65969954, 12.30241672,
14.44154148, 16.00261267, 19.98693664, 25.93076421,
30.89483997, 35.27106466, 50.81645983, 68.06009144])
xErrors = .0005*np.ones(len(xValues))
yErrors = np.array([ 0.31905094, 0.37956865, 0.24837562, 0.68320078, 1.25915789,
1.40241088, 0.33305157, 1.37165251, 0.32658393, 0.52253429,
1.04506858, 1.30633573])
wcModel = odrpack.Model(divergence)
mydata = odrpack.RealData(xValues, yValues, sx=xErrors, sy=yErrors)
myodr = odrpack.ODR(mydata, wcModel, beta0=[.8])
myoutput = myodr.run()
myoutput.pprint()
From looking at previous questions about this error I found here:
NumPy, RuntimeWarning: invalid value encountered in power
I suspected that the problem is that I'm raising a negatuve value to a power of a fractional value. But what I'm raising to the power -2.4 (1-x/xDiv) isn't negative (at least around the initial guess of xDiv=.8). But when I try to make my y-values of complex type I get a new error:
"ValueError: y could not be made into a suitable array"
from the line with the command
myoutput = myodr.run().
The only examples I can find that use this odr package are fitting to polynomials so I suspect that might be the problem?

Categories

Resources