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. (否则,浮点舍入错误可能会给您带来错误的结果。)
You can use the linspace
function from the NumPy library (which isn't part of the standard library but is relatively easy to obtain).
(您可以使用NumPy库中的linspace
函数(该库不是标准库的一部分,但相对容易获得)。)
linspace
takes a number of points to return, and also lets you specify whether or not to include the right endpoint: (linspace
需要返回多个点,还可以指定是否包括正确的端点:)
>>> 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])
If you really want to use a floating-point step value, you can, with numpy.arange
.
(如果您确实要使用浮点步进值,则可以使用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])
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: (这是一个简单的情况,当四舍五入误差仅会产生3个数字时,会导致arange
产生一个length-4数组:)
>>> numpy.arange(1, 1.3, 0.1)
array([1. , 1.1, 1.2, 1.3])