首页 > 解决方案 > 在函数图中使用浮点数作为步长

问题描述

我想绘制一个函数0.975 ≤ x ≤ 1.044 with step size 0.0001并想知道如何使用浮点数作为步长?

我要绘制的函数是y=−1+7x−21x2 +35x3 −35x4 +21x5 −7x6 +x7并且我已经计算了代码

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0.975, 1.044, 0.0001)

# calculate y for each element of x
y = x**7 - 7*x**6 + 21*x**5 - 35*x**4 + 35*x**3 - 21*x**2 + 7*x -1

fig, ax = plt.subplots()
ax.plot(x, y)

如果我将步长值替换为 int 而不是 float,则代码可以正常工作,但是当我使用 0.0001 时,会出现以下错误。有什么办法可以解决这个问题吗?

File "/opt/anaconda3/lib/python3.8/site-packages/numpy/core/function_base.py", line 117, in linspace
num = operator.index(num)

TypeError: 'float' object cannot be interpreted as an integer


During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "/Users/idalundmark/Desktop/Programmeringsteknik för matematiker (Labb)/Avklarade labbar/untitled0.py", line 13, in <module>
    x = np.linspace(0.975, 1.044, 0.0001)

  File "<__array_function__ internals>", line 5, in linspace

  File "/opt/anaconda3/lib/python3.8/site-packages/numpy/core/function_base.py", line 119, in linspace
    raise TypeError(

TypeError: object of type <class 'float'> cannot be safely interpreted as an integer.

标签: pythontypeerror

解决方案


numpy.linespace()第三个参数中表示要生成的样本数。(默认为 50)这可能是一个非负整数值。更多信息可以参考官方文档

正如@AcaNg 在评论中建议的那样,您可以numpy.arrange()改用。这也类似于linspace,但使用步长(而不是样本数)。


推荐阅读