NumPy中的arange函数出现除以零错误

7

我使用了NumPy的arange函数创建了以下范围:

a = n.arange(0,5,1/2)

这个变量本身是没有问题的,但是当我在脚本中的任何位置尝试使用它时,就会出现错误,错误消息如下:

ZeroDivisionError: 除以零


4
你的步长为零。看一下 1/2 的计算结果。 - askewchan
1
@askewchan:这取决于Python的版本。请参见下面Rob的答案。 - Benjamin Bannier
你说得对,@honk。在Python 3中看到这个错误会让我非常惊讶,所以我认为OP在使用Python 2。 - askewchan
2个回答

6

首先,在Python 2.x中,您的step将被评估为零。其次,如果您想使用非整数步长,可以查看np.linspace

Docstring:
arange([start,] stop[, step,], dtype=None)

Return evenly spaced values within a given interval.

[...]

When using a non-integer step, such as 0.1, the results will often not
be consistent.  It is better to use ``linspace`` for these cases.

In [1]: import numpy as np

In [2]: 1/2
Out[2]: 0

In [3]: 1/2.
Out[3]: 0.5

In [4]: np.arange(0, 5, 1/2.)  # use a float
Out[4]: array([ 0. ,  0.5,  1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5])

2
如果您没有使用较新版本的Python(我认为是3.1或更高版本),那么表达式1/2的值将为零,因为它假定为整数除法。
您可以通过将1/2替换为1./2或0.5来解决此问题,或者在脚本顶部添加from __future__ import division

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接