gpt4 book ai didi

python - 全局名称 'sqrt' 未定义

转载 作者:太空狗 更新时间:2023-10-30 02:04:06 26 4
gpt4 key购买 nike

我创建了一个函数,potential(x,K,B,N),其中 x,K, Bnumpy 数组,N 是一个整数。我正在尝试在 iPython 中测试函数,但我一直收到错误 “global name 'sqrt' not defined”

看看我的代码:

def potential(x,K,B,N):

x = x.reshape((3,N),order='F')

U_b = 0.0
for i in xrange(0,N-1):
for j in xrange(i+1,N):
if K[i,j] == 1.0:
U_b += sum((x[:,i]-x[:,j])**2)
U_b = 0.5*U_b

U_a = 0.0
for i in xrange(0,N-2):
for j in xrange(i+1,N-1):
for l in xrange(j+1,N):
if B[i,j,l] == 1.0:
U_a += B[i,j,l]*sum((x[:,i]-x[:,j])*(x[:,j]-x[:,l]))/(sqrt(sum((x[:,i]-x[:,j])**2))*sqrt(sum((x[:,j]-x[:,l])**2)))
U_a = -U_a

U_r = 0.0
d = 0.0
for i in xrange(0,N-1):
for j in xrange(i+1,N):
d = sqrt(sum((x[:,i]-x[:,j])**2))
if d > sqrt(0.2):
U_r += (1.0/6.0)*(1/(d**6))
else:
U_r += -0.2**(-7.0/2.0)*d + (7.0/6.0)*(0.2)**(-3)

return U_b + U_a + U_r

我试过使用 from math import * 但这似乎没有帮助。任何建议将不胜感激!

最佳答案

添加缺失的行:

from numpy import sqrt 

(或在非 NumPy 代码中 from math import sqrt。请注意,这是两个不同的函数:numpy.sqrt 也接受向量和数组,但普通的 math.sqrt 没有)

I've tried using from math import * but that doesn't seem to help.

(可能你是在定义了函数之后才这么做的。无论如何,fuhgeddaboutit,只要在一个干净的 session 中重新加载代码,它就会工作。)

更新:

  • 严格来说,在 Python 中您应该执行 import package 而不是 from package import identifier1 [,identifier2, identifier3...]从不 from package import *。但是如果明智地使用 from package import identifier1 是可以的,如果你没有过度使用它,并且在函数内部局部使用。如果它是明确的,并且你将要做很多,它会缩短代码,例如sqrt() 代替 math.sqrt()log 代替 math.log10()

  • sqrt 不是 Python 的内置函数,不像 R。所以是的,在 Python 中你需要 from numpy import sqrtimport mathfrom math import sqrt 才能使用它。

关于python - 全局名称 'sqrt' 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24320630/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com