python - 如何修复 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'
我做错了什么,如何解决这个问题以使代码运行?
解决方案
我认为您正在尝试使用^
运算符求幂。这是某些语言(如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.power
intead:
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
推荐阅读
- kubernetes - 如何检查 Kubernetes 对象是否被完全删除?
- javascript - 如何从节点中删除文本?
- python - 如何从 npy 数组创建 3d 散点图
- sql - 如何将随机值从一个表插入到另一个表(oracle sql)?
- macros - SAS 宏未运行
- xml - 用完整的命名空间 URI 值替换 XML 命名空间前缀?
- c++ - 仅用一个内环打印图案
- json - 如何在 Stackblitz 项目中加载 JSON?
- python - Pyqt5 Qt Designer 后退按钮问题
- excel - 根据 9 月 1 日至 9 月 30 日的条件,将数据从主数据复制到多个工作表