如何使用小数范围()步长值?
问题描述
有没有办法在 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])
相关文章