Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

python - 如何使用十进制range()步长值?(How to use a decimal range() step value?)

Is there a way to step between 0 and 1 by 0.1?

(有没有办法在0和1之间以0.1步进?)

I thought I could do it like the following, but it failed:

(我以为我可以像下面那样做,但是失败了:)

for i in range(0, 1, 0.1):
    print i

Instead, it says that the step argument cannot be zero, which I did not expect.

(相反,它说step参数不能为零,这是我没有想到的。)

  ask by Evan Fosmark translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...