【问题标题】:Function not callable anymore after one try一次尝试后函数不再可调用
【发布时间】:2022-01-16 15:24:29
【问题描述】:

我现在正在编写一个函数,它有一个非常奇怪的问题。当我定义函数Psi(t) 并调用它进行绘图时,它工作正常。但是,当您再次调用它进行绘图时,它会发送错误'numpy.ndarray' object is not callable。当您单击Psi(t) 上的播放(在 Jupyter 笔记本上)再次定义它然后调用它进行绘图时,它又可以正常工作了。如果要更改参数,则必须再次定义它,然后再次绘制 Psi(t)。我不知道它是否与我用于 python(VS 代码)的代码或软件有关。无论如何,这是代码:

# Constants
m = 9.109e-31           # mass of electron in kg
L = 1e-8                # length of box in m
hbar = 1.0546e-34       # hbar in J/s
x0 = L/2                # midpoint of box
sigma = 1e-10           # width of wave packet in m
kappa = 5e10           # wave number in 1/m
N = 1000                # number of grid slices

def psi0(x):
    return np.exp( -(x - x0)**2/(2*sigma**2) )*np.exp(-1j*kappa*x)

#Discrete sine transform
def dst(y):
    N = len(y)
    y2 = np.empty(2*N,float)
    y2[0] = y2[N] = 0.0
    y2[1:N] = y[1:]
    y2[:N:-1] = -y[1:]
    a = -np.imag(rfft(y2))[:N]
    a[0] = 0.0

    return a

#Inverse discrete sine transform
def idst(a):
    N = len(a)
    c = np.empty(N+1,complex)
    c[0] = c[N] = 0.0
    c[1:N] = -1j*a[1:]
    y = irfft(c)[:N]
    y[0] = 0.0

    return y

x_n = np.zeros(N, complex)
xgrid = range(N)

for i in range(N):
    x_n[i] = psi0(i*L/N)

alpha = dst(np.real(x_n))
eta = dst(np.imag(x_n))

def Psi(t):
    k = np.arange(1, N+1)
    energy_k = (k**2*np.pi**2*hbar)/(2*m*L**2) 
    cos, sin = np.cos(energy_k*t), np.sin(energy_k*t)
    
    re_psi = alpha*cos - eta*sin
    im_psi = eta*cos + alpha*sin
    psi = re_psi + im_psi

    return idst(psi)

Psi = Psi(2e-16)

plt.plot(xgrid,Psi)
plt.show()

希望有人能帮忙。

【问题讨论】:

  • 您正在用 Psi = Psi(2e-16) 覆盖对函数 Psi 的引用。您的意思可能是 psi = Psi(2e-16)

标签: python arrays numpy callable


【解决方案1】:

倒数第三行:

Psi = Psi(2e-16)

您正在将函数对Psi 的引用更新为返回值。这样做后,Psi 不能再用作函数。建议不要在代码中使用与函数或类同名的变量。解决方案是重命名变量,或者重命名函数和函数调用。

【讨论】:

  • 哦,太好了!谢谢你们。
猜你喜欢
  • 2017-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-06
  • 1970-01-01
  • 1970-01-01
  • 2015-09-22
  • 1970-01-01
相关资源
最近更新 更多