本文介绍了如何使用十进制 range() 步长值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

 for i in range(0, 1, 0.1):打印我

相反,它说 step 参数不能为零,这是我没想到的.

解决方案

与直接使用小数步长相比,用您想要的点数来表达这一点要安全得多.否则,浮点舍入错误很可能会给你一个错误的结果.

您可以使用 linspace 函数从NumPy 库(它不是标准库的一部分,但相对容易获得).linspace 需要返回多个点,还可以让您指定是否包含正确的端点:

>>>np.linspace(0,1,11)数组([ 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)数组([ 0., 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])

如果你真的想使用浮点步长值,你可以使用 numpy.arange.

>>>将 numpy 导入为 np>>>np.arange(0.0, 1.0, 0.1)数组([ 0., 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])

但是,

浮点舍入错误导致问题.这是一个简单的例子,其中舍入错误导致 arange 生成一个长度为 4 的数组,而它应该只生成 3 个数字:

>>>numpy.arange(1, 1.3, 0.1)数组([1., 1.1, 1.2, 1.3])

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

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.

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

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

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

这篇关于如何使用十进制 range() 步长值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 11:45