15

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))
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
Ali R.
  • 433
  • 2
  • 4
  • 11
  • 2
    arccos is only defined in the range `[-1,1]`. See ["domain" in the numpy docs](http://docs.scipy.org/doc/numpy/reference/generated/numpy.arccos.html). You feed it a number > 1. – Boldewyn Feb 10 '16 at 15:08
  • 2
    I came here because sometimes the input to arccos was only slightly larger than 1. (due to numerical precision). I solved it with np.arccos(np.minimum(1, array)) – gota Sep 22 '17 at 11:12
  • 2
    Alternative to @gota which accounts for negative values too: `np.arccos(np.around(array,4))` – Nigu Feb 28 '19 at 08:56

2 Answers2

16

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
ti7
  • 16,375
  • 6
  • 40
  • 68
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
  • Silly of me! Should've known that! Guess there is an error in my calculations then. Thanks for your help! – Ali R. Feb 10 '16 at 17:58
8

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

aefxx
  • 24,835
  • 6
  • 45
  • 55
ramblinknight
  • 81
  • 1
  • 1