从插值函数中检索值

时间:2013-05-17 10:50:48

标签: python numpy scipy interpolation

我是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()

奇怪的是,只有当我将整个数组用作参数inter(aa)时,我的MWE才有效,它返回一个内插点列表。 我无法弄清楚为什么第一个例子有效,而第二个例子没有。两个数组看起来都是一样的,但只有第一个例子实际上产生了一个输出。

编辑:添加返回的错误

---------------------------------------------------------------------------
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范围内。

1 个答案:

答案 0 :(得分:1)

req()的结果是一个sympy对象而不是真正的Python float,因此,uplmt也是一个sympy对象。 numpy的数值例程不知道如何处理这些同情对象。尽早转换为Python float对象。

在我的机器上,r0r1的值实际上很复杂,只有很小的虚构组件,并且它们会比您显示的错误更早地导致错误。但是转换它们很容易:

# upper and lower limits on r
r1 = complex(req(E0)[1]).real
r0 = complex(req(E0)[2]).real

在我做出更改后,您的脚本会为我完成,但我不能保证它会为您提供所需的数值结果。