【发布时间】:2021-01-19 11:29:21
【问题描述】:
我编写了一个程序,通过公式计算无穷和级数。我使用了一个范围函数来计算它,但我遇到了一个问题,即范围不适用于浮点数。
TypeError: 'float' object cannot be interpreted as an integer
我尝试使用numpy.arrange,但只有在您想使用步骤arrange(start, stop, STEP)时才有帮助。
import math
import numpy
x = float(input('x: '))
n = float(input('n: '))
s = 0
while x >= 0.1:
for i in range(1, n + 1):
s = s + (math.pow(-1, i) * math.pow(x, 4 * i + 3)) / (numpy.factorial(2 * i + 1) * (4 * i + 3))
if x >= 1:
break
print(s)
UPD:这是我的程序现在的样子:` 导入数学 导入numpy
x = float(input('x: '))
n = int(input('n: '))
s = 0
while x >= 0.1:
for i in range(1, n + 1):
s = s + (math.pow(-1, i) * math.pow(x, 4 * i + 3)) / (math.factorial(2 * i + 1) * (4 * i + 3))
if x >= 1:
break
print(s)
` 这样的输出:
W:\Labaratorni\Python\lab2_4\venv\Scripts\python.exe
W:/Labaratorni/Python/lab2_4/main.py
x: 0.3
n: 3
没有错误,它只是停止。
【问题讨论】:
-
您不能使用浮点数作为
range的参数。另外,修正你的缩进。 -
但是
n = int(input('n: '))应该可以解决问题。 -
所以如果我想计算这个我需要使用别的东西而不是范围?
-
@alani 是的,但我需要使用花车,这是一项任务
-
不清楚你到底想要什么。
range(1, some_float + 1)会做什么?例如range(1, 3.5)?也许,你可以只使用一个while循环。
标签: python python-3.x math