python - 类型错误 : unsupported operand type(s) for ^: 'numpy.float64' and 'numpy.float64'

标签 python python-2.7 numpy

我刚开始用 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 - 类型错误 : unsupported operand type(s) for ^: 'numpy.float64' and 'numpy.float64' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30084905/

相关文章:

python - `G` 类型的python % 字符串格式如何表现?

python - 在Python中从字典列表构建深度嵌套字典的最有效方法

python - 在命令行中将文件名传递给 python 脚本

python - numpy中唯一元素的分组索引

python - 如何在 python 中从 sys.stdin 输入矩阵而不丢失其二维结构,同时能够对其使用 numpy 运算?

javascript - 使用 selenium 抓取 Tripadvisor 时如何单击 "More"按钮?

python - 使用带有 View 函数的 webapp2 微框架时如何呈现模板?

python - OpenCV 中的 Flann KNN Matcher 只返回一个点而不是一对

python - 如何通过匹配列名从稀有标签中解码列值

python - Itertools 链在 Cython 中的行为有所不同