numpy.arange除以零错误

bla*_*kbk 6 python numpy

我使用了numpy的arange函数来制作以下范围:

a = n.arange(0,5,1/2)
Run Code Online (Sandbox Code Playgroud)

这个变量本身很好用,但是当我尝试将它放在我的脚本中的任何地方时,我得到一个错误

ZeroDivisionError:除以零

roo*_*oot 6

首先,你的step计算结果为零(在python 2.x上).其次,您可能想要检查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.
Run Code Online (Sandbox Code Playgroud)
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])
Run Code Online (Sandbox Code Playgroud)