How to use a decimal range() step value?(如何使用小数范围()步长值?)
问题描述
有没有办法在 0 和 1 之间步进 0.1?
Is there a way to step between 0 and 1 by 0.1?
我以为我可以这样做,但它失败了:
I thought I could do it like the following, but it failed:
for i in range(0, 1, 0.1):
print i
相反,它说 step 参数不能为零,这是我没想到的.
Instead, it says that the step argument cannot be zero, which I did not expect.
推荐答案
比起直接使用小数步长,用你想要的点数来表达要安全得多.否则,浮点舍入错误很可能会给你一个错误的结果.
Rather than using a decimal step directly, it's much safer to express this in terms of how many points you want. Otherwise, floating-point rounding error is likely to give you a wrong result.
您可以使用 linspace 函数NumPy 库(它不是标准库的一部分,但相对容易获得).linspace 需要返回多个点,还可以让您指定是否包含正确的端点:
You can use the linspace function from the NumPy library (which isn't part of the standard library but is relatively easy to obtain). linspace takes a number of points to return, and also lets you specify whether or not to include the right endpoint:
>>> np.linspace(0,1,11)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
>>> np.linspace(0,1,10,endpoint=False)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
如果你真的想使用浮点步进值,你可以使用 numpy.arange.
If you really want to use a floating-point step value, you can, with numpy.arange.
>>> 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])
浮点舍入误差会导致问题.这是一个简单的例子,其中舍入错误导致 arange 在它应该只产生 3 个数字时产生一个长度为 4 的数组:
Floating-point rounding error will cause problems, though. Here's a simple case where rounding error causes arange to produce a length-4 array when it should only produce 3 numbers:
>>> numpy.arange(1, 1.3, 0.1)
array([1. , 1.1, 1.2, 1.3])
这篇关于如何使用小数范围()步长值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用小数范围()步长值?
基础教程推荐
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 包装空间模型 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 求两个直方图的卷积 2022-01-01
