首页 > 解决方案 > 如何修复 TypeError:不支持的操作数问题

问题描述

我正在用 Python 编写一个函数,product_z它计算 (N^z)/z * ∏ k/z+k 从 k=1 到 N 的乘积。

代码如下所示;

import numpy as np

def z_product(z,N):
    terms = [k/(z+k) for k in range(1,N+1)]
    total = (N^z/z)*np.prod(terms)
    return total

但是,例如,我正在使用此输入运行代码,但我得到一个 TypeError 作为回报。

"Check that z_product returns the correct datatype."
assert type(z_product(2,7)) == np.float64 , "Return value should be a NumPy float."
print("Problem 2 Test 1: Success!")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-d2e9161f328a> in <module>()
      1 "Check that z_product returns the correct datatype."
----> 2 assert type(z_product(2,7)) == np.float64 , "Return value should be 
a NumPy float."
      3 print("Problem 2 Test 1: Success!")

<ipython-input-8-1cd27b06388f> in z_product(z, N)
      1 def z_product(z,N):
      2     terms = [k/(z+k) for k in range(1,N+1)]
----> 3     total = (N^z/z)*np.prod(terms)
      4     return total

TypeError: unsupported operand type(s) for ^: 'int' and 'float'

我做错了什么,如何解决这个问题以使代码运行?

标签: pythonarraysnumpy

解决方案


我认为您正在尝试使用^运算符求幂。这是某些语言(如R或 MATLAB)中正确的运算符,但不是正确的 python 语法。在 Python 中,^运算符代表 XOR。改为使用**

def z_product(z,N):
    terms = [k/(z+k) for k in range(1,N+1)]
    total = (N**z/z)*np.prod(terms)
    return total

>>> z_product(2,7)
0.6805555555555555

或者,您可以使用np.powerintead:

def z_product(z,N):
    terms = [k/(z+k) for k in range(1,N+1)]
    total = (np.power(N,z)/z)*np.prod(terms)
    return total

推荐阅读