【问题标题】:How to interpret int to float for range function? [duplicate]如何将 int 解释为范围函数的浮点数? [复制]
【发布时间】: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


【解决方案1】:

我相信这应该做你想做的:

import math

x = float(input('x: '))
n = int(input('n: '))
s = 0
if 0.1 <= x <= 1:
    for i in range(1, n + 1):
        s += ((-1)**i * x**(4 * i + 3)) / (math.factorial(2*i + 1) * (4*i + 3))
        
print(s)

重点是 range 函数必须接受整数,所以你必须将 n 转换为 int。

我认为您在应该使用 if 语句的地方使用了 while 循环。如果我们误解了您的目标,请告诉我们,明确说明总和应该是什么可能会有所帮助。

【讨论】:

  • 帮了很多忙
猜你喜欢
  • 2014-02-25
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-06
  • 1970-01-01
相关资源
最近更新 更多