Skip to main content
 首页 » 编程设计

python之从插值函数中检索值

2025年05月04日8insus

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

请您参考如下方法:

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

在我的机器上,r0 和 r1 的值实际上是复杂的,只是带有微小的虚部,并且它们比您显示的更早导致错误。不过,转换它们很容易:

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

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