Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.arange divide by zero error

Tags:

python

numpy

I have used numpy's arange function to make the following range:

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

This variable works fine by itself, but when I try putting it anywhere in my script I get an error that says

ZeroDivisionError: division by zero

like image 833
blaylockbk Avatar asked May 14 '13 19:05

blaylockbk


People also ask

How to ignore division by zero in NumPy existing?

# ignore division by zero in numpy existing = numpy.seterr (divide="ignore") # upcast `1.0` to be a numpy type so that numpy division will always occur x = numpy.where (b == 0, a, numpy.float64 (1.0) / b) # restore old error settings for numpy numpy.seterr (*existing) If x and y are given and input arrays are 1-D, where is equivalent to::

What is arange in NumPy?

NumPy is the fundamental Python library for numerical computing. Its most important type is an array type called ndarray. NumPy offers a lot of array creation routines for different circumstances. arange() is one such function based on numerical ranges. It’s often referred to as np.arange() because np is a widely used abbreviation for NumPy.

What are the arguments of NumPy array?

The function np.arange() is one of the fundamental NumPy routines often used to create instances of NumPy ndarray. It has four arguments: start: the first value of the array; stop: where the array ends; step: the increment or decrement; dtype: the type of the elements of the array

How do I Divide an array by zero in Python?

Division by zero always yields zero in integer arithmetic (again, Python 2 only), and does not raise an exception or a warning: >>> np . divide ( np . array ([ 0 , 1 ], dtype = int ), np . array ([ 0 , 0 ], dtype = int )) array([0, 0])


2 Answers

First, your step evaluates to zero (on python 2.x that is). Second, you may want to check np.linspace if you want to use a non-integer step.

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])
like image 90
root Avatar answered Nov 14 '22 21:11

root


If you're not using a newer version of python (3.1 or later I think) the expression 1/2 evaluates to zero, since it's assuming integer division.

You can fix this by replacing 1/2 with 1./2 or 0.5, or put from __future__ import division at the top of your script.

like image 44
Rob Falck Avatar answered Nov 14 '22 20:11

Rob Falck