我对 python 很陌生,作为一个项目,我决定用 python 编写我的 Mathematica 项目以查看它是如何工作的,因此代码的编写方式尽可能接近 Mathematica。
我正在努力从插值函数中调用一个值,在一个简单的工作示例中,我想这样做:
import numpy as np
from scipy.interpolate import interp1d
a = np.linspace(1,10,10)
b = np.sin(a)
inter = interp1d(a,b)
# this is where i get a value from the interpolated function
s0 = inter(a[0])
print(s0)
这是我的 MWE 不起作用:
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from sympy import *
from scipy import integrate
from scipy.interpolate import interp1d
E0 = -0.015
L = 5.5
Ns = 1000
# this solves for where the energy E0 intersects the potential y
def req(E0):
L=5.5
r = Symbol('r')
y = -(2*L**2)/(r**3)+(L**2)/(r**2)-(2)/(r)
rr = (E0-y)*(r**4)
rreq = Eq(rr, 0)
rrt = sorted(solve(rr), key=int)
return rrt
# upper and lower limits on r
r1 = req(E0)[1]
r0 = req(E0)[2]
# initialise the arrays
a = np.array([1])
b = np.array([1])
# numerically integrate the function R(r)
for n in range(2, Ns):
# integrate
lwlmt = r0
uplmt = r0+(n-1)*(r1-r0)/(Ns-1)
result, error = integrate.quad(lambda ra: -1/((E0-(-(2*L**2)/(ra**3)+(L**2)/(ra**2)-(2)/(ra)))*(ra**4))**(0.5), r0, uplmt)
a = np.append([uplmt],[[a]])
b = np.append([result],[[b]])
# chop the 1 from the end
aa = a[:-1]
ba = b[:-1]
# interpolate
inter = interp1d(aa,ba)
# this is the problem
print(inter(110))
# this is what i would ideally like to do,
# get the start and end points however i receive an error
s0 = inter(aa[0])
s1 = inter(aa[len(aa)-1])
plt.plot(aa,inter(aa))
plt.show()
奇怪的是,我的 MWE 仅在我使用整个数组作为参数时才有效,inter(aa)
它返回一个插值点列表。我无法弄清楚为什么第一个示例有效,而第二个示例无效。两个数组看起来是相同的,但是只有第一个示例实际产生了输出。
编辑:添加返回的错误
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/home/nick/Documents/python/<ipython-input-4-b36b3f397c2e> in <module>()
45 # this is what i would ideally like to do,
46 # get the start and end points
---> 47 s0 = inter(aa[1])
48 s1 = inter(aa[len(aa)-1])
49
/usr/lib/python2.7/dist-packages/scipy/interpolate/interpolate.pyc in __call__(self, x_new)
364 # from y_new and insert them where self.axis was in the list of axes.
365 nx = x_new.ndim
--> 366 ny = y_new.ndim
367
368 # 6. Fill any values that were out of bounds with fill_value.
AttributeError: 'Float' object has no attribute 'ndim'
这是我在 val 参数中输入的任何数字的错误inter([val])
,即在aa
.