python - 在函数图中使用浮点数作为步长
问题描述
我想绘制一个函数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.
解决方案
在numpy.linespace()
第三个参数中表示要生成的样本数。(默认为 50)这可能是一个非负整数值。更多信息可以参考官方文档
正如@AcaNg 在评论中建议的那样,您可以numpy.arrange()
改用。这也类似于linspace
,但使用步长(而不是样本数)。
推荐阅读
- python - 使用 pysinstaller 构建 python 项目后找不到模块
- python - 如何找到在 30 天内进行第二次购买的客户?
- spring - 在 Spring Boot 中处理 @SqsListener 处理失败的最佳方法是什么?
- java - 如何使用价值'?attr / actionButtonStyle制作'风格'
- python - 如何在python中连接docx文件?
- laravel - 为什么游标分页不适用于 laravel 中的关系?
- python - 我想加载 Hiroki Taniai 的预训练 faecnet_keras.h5 模型,但得到了 ValueError
- c++11 - 什么样的引用应该在 C++ 中使用具有移动语义的 move() 成员函数?
- vba - 从其他模块调用全局配置变量的更好方法
- python - 熊猫数据框熊猫