【问题标题】:TypeError: unsupported operand type(s) for ^: 'numpy.float64' and 'numpy.float64'类型错误:^ 不支持的操作数类型:“numpy.float64”和“numpy.float64”
【发布时间】:2015-05-06 18:35:12
【问题描述】:

我刚开始使用 Python 进行编程,并且对 Numpy 包非常陌生……我仍在努力掌握它。我正在尝试使用 euler 方法解决函数。

这是我的代码:

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 (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'

有人知道哪里出了问题或有什么建议吗?

【问题讨论】:

  • 感谢您的回复!

标签: python python-2.7 numpy


【解决方案1】:

插入符运算符 (^) 不是幂运算。它是按位异或,仅对整数有意义。你想要**

【讨论】:

    猜你喜欢
    • 2018-06-19
    • 2013-01-02
    • 1970-01-01
    • 2016-10-15
    • 2019-10-11
    • 2017-05-27
    • 2014-06-15
    • 2012-11-01
    • 2019-04-08
    相关资源
    最近更新 更多