2

我对 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.

4

1 回答 1

1

的结果req()是一个 sympy 对象,而不是一个真正的 Python 浮点数,因此,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

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

于 2013-05-17T12:34:25.150 回答