Skip to main content
v2026.11,986 entries · CC-BY 4.0

NumPy Divide: np.divide Syntax, where=, out= and Division by Zero

np.divide returns the element-wise quotient of two arrays. Learn the safe where= and out= pattern, divide-by-zero results, and how it differs from //.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

np.divide(x1, x2) returns the element-wise quotient of two arrays or scalars, and it is what the / operator calls on NumPy arrays. This guide covers the syntax, the safe-division pattern that combines where= with out=, what happens when the divisor is zero, and how divide differs from floor_divide and //. Outputs below were run on NumPy 2.5.1 and match the NumPy reference documentation.

What np.divide is used for in research

numpy.divide computes x1 / x2 element by element. Typical research uses are normalising counts by totals, converting raw measurements to rates or ratios, and scaling each column of a data matrix by a per-column factor. If the two inputs have different shapes they must be broadcastable to a common shape, which becomes the shape of the output (see NumPy broadcasting). The result is a scalar when both inputs are scalars, otherwise an array.

The NumPy documentation states that true_divide(x1, x2) is an alias for divide(x1, x2), and that / can be used as shorthand for np.divide on ndarrays.

Install or access

NumPy is installed with python -m pip install numpy and imported by convention as np (see import numpy as np). The function documentation lives in the NumPy reference page for numpy.divide.

Step-by-step: divide arrays with np.divide

1. Divide two values or arrays

  1. Import NumPy: import numpy as np
  2. Call the function: np.divide(2.0, 4.0) returns 0.5.
  3. For arrays, pass two broadcastable arrays. With x1 = np.arange(9.0).reshape((3, 3)) and x2 = np.arange(3.0), np.divide(x1, x2) divides every row of x1 by x2.

The signature in the current reference is numpy.divide(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True). Here x1 is the dividend and x2 the divisor.

2. Divide safely: where= together with out=

The documentation says that at locations where where is True the output is set to the result, and elsewhere the output keeps its original value. If out was not supplied, the positions where where is False stay uninitialized. That is the trap: where= on its own does not give you zeros. Always pass a pre-filled out.

import numpy as np
a = np.array([4., 0., 6., 0.])
b = np.array([2., 0., 0., 5.])

out = np.zeros_like(a)
np.divide(a, b, out=out, where=b != 0)
# array([2., 0., 0., 0.])

Here positions where the divisor is zero keep the pre-filled value 0.0 and no warning is raised, because the division is never performed there. Choose the fill value to suit your analysis (zeros, np.nan, or another sentinel), and record that choice in your methods notes.

Output and how to read it

With the same a and b, a plain np.divide(a, b) returns array([ 2., nan, inf, 0.]) and emits two RuntimeWarnings. The 2D example from the NumPy reference returns:

array([[nan,  1.,  1. ],
       [inf,  4.,  2.5],
       [inf,  7.,  4. ]])
  • inf is a finite number divided by zero. The seterr documentation describes “Division by zero” as an infinite result obtained from finite numbers.
  • nan is the result of 0/0 and is reported under the separate invalid category. Downstream statistics need to handle it deliberately (see NumPy NaN).

Dividing integer arrays still produces floating-point results: np.divide(7, 2) returns 3.5, and an integer array divided by 2 comes back as float64.

Control division-by-zero warnings

numpy.errstate is a context manager that sets floating-point error handling for the block it wraps (usable as a decorator since NumPy 1.17.0). Its keywords are divide, over, under and invalid, and each takes one of 'ignore', 'warn', 'raise', 'call', 'print', 'log'. In the seterr reference, ignore means take no action, warn prints a RuntimeWarning, and raise raises a FloatingPointError.

with np.errstate(divide='raise'):
    np.divide(np.array([1.]), np.array([0.]))
# FloatingPointError: divide by zero encountered in divide

with np.errstate(divide='ignore'):
    np.arange(3) / 0.
# array([nan, inf, inf])  (silently)

Zero over zero is reported under invalid, not divide, so to make both fail loudly use np.errstate(divide='raise', invalid='raise'). To see the settings active in your session, call np.geterr(); on NumPy 2.5.1 it returned {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}. np.seterr(**old) restores a saved dictionary.

Troubleshooting

“RuntimeWarning: divide by zero encountered in divide”

At least one divisor was zero. Mask those positions with where=x2 != 0 and a pre-filled out, or set the handling explicitly with np.errstate.

“RuntimeWarning: invalid value encountered in divide”

A 0/0 (or inf/inf) produced nan. Use the same mask, and check upstream data for empty groups.

Garbage values where the mask was False

You used where= without out=. Per the documentation those locations are uninitialized; pass out=np.zeros_like(x1, dtype=float) or another initial array.

“operands could not be broadcast together”

The shapes are not compatible. Reshape one input or add an axis, as described in NumPy broadcasting.

np.divide vs / vs floor_divide vs //

Expression What it returns Example
x1 / x2 Same as np.divide on ndarrays x1 / (2*np.ones(3))
np.true_divide(x1, x2) Alias for np.divide np.true_divide(7, 2) gives 3.5
np.floor_divide(x1, x2) Largest integer smaller than or equal to the quotient np.floor_divide(7, 3) gives 2
x1 // x2 Python operator equivalent of floor_divide np.floor_divide([1., 2., 3., 4.], 2.5) gives [0., 0., 1., 1.], as does x1 // 2.5

Floor division rounds toward negative infinity, so np.floor_divide(-7, 2) returns -4 while -7 / 2 is -3.5. The documentation notes that floor_divide pairs with the remainder operator so that a = a % b + b * (a // b) holds up to roundoff. If you want to round a true quotient instead, see NumPy round and NumPy floor. For the related issue of dividing by N - ddof when computing variance, see NumPy std.

Free alternatives

NumPy is free, and so are the tools below. Pick the one that matches the data you already hold.

Alternative What it does for division Official documentation Cost
Python / on plain numbers True division of two scalars. Division by zero raises ZeroDivisionError instead of returning inf or nan. https://docs.python.org/3/reference/expressions.html Free, ships with Python
pandas.Series.div Equivalent to series / other, with a fill_value argument to substitute for missing data in either input. https://pandas.pydata.org/docs/reference/api/pandas.Series.div.html Free, open source

For arrays, np.divide remains the option with where= and out= control, as shown above.

Frequently asked questions

Is np.divide the same as the / operator?

For NumPy arrays, yes. The documentation says / can be used as shorthand for np.divide. Use the function form when you need out=, where= or dtype=.

Is np.true_divide different from np.divide?

No. true_divide is an alias for divide.

What does np.divide return for division by zero?

inf for a nonzero finite number over zero and nan for zero over zero, with a RuntimeWarning under the default settings shown by np.geterr() above.

How do I divide only where the divisor is nonzero?

Use np.divide(a, b, out=np.zeros_like(a), where=b != 0).

Sources

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about NumPy Divide: np.divide Syntax, where=, out= and Division by Zero

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →