gpt4 book ai didi

python - Python 3.4 中的函数绘图器显示 'float is not interpreted as an integer' ?

转载 作者:行者123 更新时间:2023-12-01 05:28:25 27 4
gpt4 key购买 nike

import numpy as np
import matplotlib.pyplot as plt
print("FUNCTION GRAPHER")
def graph(formula,domain):
x = np.array(domain)
y = eval(formula)
plt.plot(x, y)
plt.show()
formula=input("Function: ")
domainmin=float(input("Min X Value: "))
domainmax=float(input("Max X Value: "))
graph(formula, range(domainmin,domainmax))

这是我创建图形绘制器的代码。正如您所看到的,用户可以输入函数和域。我正在使用简单的 y=x 函数对其进行测试,这是我得到的错误。我猜这与我设置输入的方式有关。

FUNCTION GRAPHER
Function: x
Min X Value: -1
Max X Value: 10
Traceback (most recent call last):
File "/Users/William/Documents/Science/PYTHON/Grapher.py", line 12, in <module>
graph(formula, range(domainmin,domainmax))
TypeError: 'float' object cannot be interpreted as an integer

发生错误后我输入:

graph('x', range(-1,10))

图表就会弹出。我使用的是 Python 3.4。

最佳答案

来自documentation :

The arguments to the range constructor must be integers

因此,要在这种情况下使用 range,您需要将代码更改为:

domainmin=int(input("Min X Value: "))
domainmax=int(input("Max X Value: "))

或者,也许更接近您的意图,您可以改用 numpy.arangenumpy.linspace ,因此您可以使用 float 范围 - 您必须另外添加粒度参数(step for arange)或步骤数( num 代表 linspace)。

关于python - Python 3.4 中的函数绘图器显示 'float is not interpreted as an integer' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20872571/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com