Matplotlib的'Float'错误

问题描述 投票:0回答:1

我正在尝试编写一个程序来绘制等式的图形

y = 5 * e ^ -t * cos(2 * pi * t)

我必须使用导入数学,这就是我所拥有的:

import matplotlib.pyplot as plt

import math

x = range(10)

y = [5 * math.exp(-t) * math.cos(math.pi * 2 * t) for t in x]

plt.plot(x,y)

plt.show()

我没有得到我想要的图表。我需要x增加0.1但是当我制作range(0, 10, .1)时,它会给我一个错误:

float不能解释为整数

如何调整代码以使我的绘图点以0.1分隔?

math matplotlib import floating-point
1个回答
1
投票

range只接受所有参数的整数值(min,max和step) - 请参阅documentation

要创建浮点范围,可以使用numpy.arangesource):

>>> import numpy as np
>>> np.arange(0.0, 1.0, 0.1)
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])

或者通过另一种理解手动完成:

>>> x = range(0, 10, 1)
>>> x_float = [0.1 * i for i in x]
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]

用法:

y = [5 * math.exp(-t) * math.cos(math.pi * 2 * t) for t in x_float] # note difference
plt.plot(x_float,y) # and here
© www.soinside.com 2019 - 2024. All rights reserved.