Python 如何修复TypeError:不支持的操作数问题
我正在用Python product_z编写一个函数,它计算 N^z/z*∏ k/z+k从k=1到N 代码如下所示Python 如何修复TypeError:不支持的操作数问题,python,arrays,numpy,Python,Arrays,Numpy,我正在用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_pr
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'
我做错了什么?如何修复此错误以使代码运行?我认为您正在尝试使用^操作符进行指数运算。在某些语言(如R或MATLAB)中,这是正确的运算符,但不是正确的python语法。在Python中,^运算符代表XOR。改用**: 或者,您可以使用intead:
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
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