我编写了一个简单的程序,它使用数值积分来近似评估定积分。但是,当谈到为什么我在标题中出现错误时,我感到很困惑。请记住,我已经有一年半没有接触过 python 了,所以我可能会很明显地错过了一些东西,但是如果你能帮助我,我仍然会很感激 :) 这是代码:
import math
def f(x):
f=math.sqrt(1+(6*x+4)^2)
return f
lbound=int(input("Input lower bound for the integral"))
ubound=int(input("Input upper bound for the integral"))
n=int(input("Input number of intervals"))
dx=((ubound-lbound)/n)
integral=0
for i in range(1,n):
integral=integral+dx*f(i*dx)
print (integral)
这是 IDLE 在尝试运行代码时给我的完整错误报告:
Traceback (most recent call last):
File "C:\Users\******\Desktop\integrals.py", line 13, in <module>
integral=integral+dx*f(n*dx)
File "C:\Users\******\Desktop\integrals.py", line 3, in f
f=math.sqrt(1+(6*x+4)^2)
TypeError: unsupported operand type(s) for ^: 'float' and 'int'
最佳答案
Python 的幂运算符是 **
,而不是 ^
。 ^
是按位异或。
f=math.sqrt(1+(6*x+4)**2)
关于Python 类型错误 : unsupported operand type(s) for ^: 'float' and 'int' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34258537/