The MWE below shows that vectorize
returns zeros instead of the actual values. Compare the printout from within the function to the arrays returned in the second test. It is curious that the first test with hollow=False
returns the correct result. Is this a bug or a not so obvious limitation of vectorize
?
In [1]: run potentials-test.py
potential r in < R: 0.2 -0.0 False
potential r in < R: 0.2 -0.0 False
potential r in < R: 0.4 -0.1 False
potential r in < R: 0.6 -0.2 False
potential r in < R: 0.8 -0.3 False
potential r in >= R: 1.0 -1.0
potential r in >= R: 1.2 -0.8
potential r in >= R: 1.4 -0.7
potential r in >= R: 1.6 -0.6
potential r in >= R: 1.8 -0.6
potential r in >= R: 2.0 -0.5
[-0.02 -0.08 -0.18 -0.32 -1. -0.83333333
-0.71428571 -0.625 -0.55555556 -0.5 ]
potential r in < R: 0.2 -1.0 True
potential r in < R: 0.2 -1.0 True
potential r in < R: 0.4 -1.0 True
potential r in < R: 0.6 -1.0 True
potential r in < R: 0.8 -1.0 True
potential r in >= R: 1.0 -1.0
potential r in >= R: 1.2 -0.8
potential r in >= R: 1.4 -0.7
potential r in >= R: 1.6 -0.6
potential r in >= R: 1.8 -0.6
potential r in >= R: 2.0 -0.5
[-1 -1 -1 -1 -1 0 0 0 0 0]
The MWE code is:
from numpy import *
from math import pi
class sphere():
def __init__(self, GM=1, R=1, hollow=True):
self.GM = GM
self.R = R
self.Grho = (3/(4*pi))*GM/R**3
self.hollow = hollow
self.vpotential = vectorize(self.potential)
def potential(self, r):
if r >= self.R:
res = -self.GM*self.R/r
print("potential r in >= R: %3.1f %5.1f"% (r, res))
return res
else:
if self.hollow:
res = -self.GM
print("potential r in < R: %3.1f %5.1f "% (r, res), self.hollow)
return res
else:
res = -(2*pi/3)*self.Grho*r**2/self.R**2
print("potential r in < R: %3.1f %5.1f "% (r, res), self.hollow)
return res
x=linspace(0.2,2,10)
s = sphere(hollow=False)
print(s.vpotential(x))
h = sphere(hollow=True)
print(h.vpotential(x))