类型错误:不支持使用^运算符进行操作的类型为“numpy.float64”和“numpy.float64”。

5

我刚开始学习Python编程,对Numpy包非常陌生......我仍在尝试理解它。我正在尝试使用欧拉方法解决一个函数。

以下是我的代码:

Z=4
B=8
U=1
C=4

a,b=(0.0,10.0)
n=2000
x0=-1.0
t=linspace (a,b,n)
#-----------------------------------------------------------------------------
def euler (f,x0,t):
    n=len (t)
    x=np.array(n*[x0,])
    for i in xrange (n-1):
        float (x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ))
    return x



#---------------------------------------------------------------------------------          
if __name__=="__main__":


    def f(x,t): 
        return float((Z)*[-(1/6)*B*C*x^3+0.5*U*t^2])


    #numerical solutions
    x_euler=euler(f,x0,t)


    #figure
    plt.plot (t,x_euler, "b")
    xlabel (t)
    ylabel (x)
    legend ("Euler")

    show()

我对这类问题的相似解决方案不太满意。以下是我的Traceback:

Traceback (most recent call last):
  File "C:\Python27\testeuler.py", line 45, in <module>
    x_euler=euler(f,x0,t)
  File "C:\Python27\testeuler.py", line 31, in euler
    float (x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ))
  File "C:\Python27\testeuler.py", line 41, in f
    return float((Z)*[-(1/6)*B*C*x^3+0.5*U*t^2])
TypeError: unsupported operand type(s) for ^: 'numpy.float64' and 'numpy.float64'

有人知道可能出了什么问题或有什么建议吗?


谢谢您的回复! - Mlle Blanche
1个回答

20

插入符号 (^) 不是指数运算符。它是按位异或运算符,只对整数有意义。你应该使用 ** 来进行指数运算。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接