Skip to main content
v2026.11,858 entries · CC-BY 4.0
LAC HealthMedical & Research SuppliesReagents, PPE & instruments — chain-of-custody documented.Fast, traceable sourcing built for regulated research environments, from bench consumables to instrumentation.Shop lac.us CodeCASRAIlac.us

NumPy Square: np.square Syntax, dtype and Overflow

How np.square works: element-wise squaring, dtype and overflow, out and where, x**2 versus np.power, and why it is not matrix squaring.

Written and maintained by CASRAI Editorial Board

Last updated

numpy.square returns the element-wise square of its input: each value multiplied by itself, in an array of the same shape and dtype as the input (or a scalar if you pass a scalar). It is a NumPy ufunc, so it works on whole arrays without a Python loop. The part most tutorials skip is the dtype: because the result keeps the input dtype, fixed-size integer types can wrap around, and that is covered under Troubleshooting below.

What np.square is used for in research

Squaring every value in an array is the building block behind squared deviations, squared residuals and sum-of-squares calculations. For example, the sum of squares used in variance and standard deviation starts by squaring each deviation from the mean; see the sum of squares formula and how np.std computes standard deviation. Squaring is also the inverse of taking a root: if you need the opposite operation, see np.sqrt.

The NumPy reference signature is numpy.square(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature]). The input x is any array_like. The return value is “element-wise x*x, of the same shape and dtype as x”, and a scalar if x is a scalar.

Install or access

The only prerequisite for installing NumPy is Python itself, according to the official install page. Commands as written there:

  • pip install numpy
  • uv pip install numpy
  • conda install numpy (inside an environment created with conda create -n my-env and activated with conda activate my-env)
  • pixi add numpy

To keep a project isolated, create a virtual environment first: python -m venv my-env, activate it with source my-env/bin/activate (macOS and Linux) or my-env\Scripts\activate (Windows), then run pip install numpy. Confirm the install with import numpy as np; print(np.__version__). If that raises an ImportError, NumPy has a dedicated troubleshooting page for it.

Step-by-step: square an array with np.square

  1. Import NumPy. import numpy as np
  2. Pass an array_like. A list, tuple or ndarray all work: np.square([1, 2, 3]) returns array([1, 4, 9]). A scalar returns a scalar: np.square(-3) returns 9.
  3. Handle complex input if you have it. The reference example is np.square([-1j, 1]), which returns array([-1.-0.j, 1.+0.j]).
  4. Write into an existing array with out. If out is not provided or is None, a freshly allocated array is returned. Passing out= an array of the right shape writes the result there instead.
  5. Square only some positions with where. Where the condition is True, out is set to the result; elsewhere out keeps its original value. With the default out=None, positions where the condition is False stay uninitialized, so supply out whenever you use where.
  6. Choose the dtype when you need one. Pass dtype=np.float64 to compute in 64-bit floating point (see the overflow note below).

Output and how to read it

  • Shape: the output has the same shape as the input, so a 2-D array comes back 2-D with every cell squared.
  • dtype: the documentation states the result has the same dtype as x. Integer in, integer out; float in, float out.
  • Scalar versus array: a scalar input gives a scalar result, an array input gives an ndarray.
  • Element-wise, not matrix squaring: np.square(A) multiplies each entry of A by itself. It does not compute the matrix product A @ A. The NumPy reference lists numpy.linalg.matrix_power under See Also for that purpose; for matrix products see matrix multiplication in NumPy.

Troubleshooting

Integer overflow gives a wrong, even negative, result

NumPy’s numeric types have a fixed size, and the official Data types page warns that this “may cause overflow errors when a value requires more memory than available in the data type.” Its documented example uses numpy.power: 100 ** 9 evaluates correctly for 64-bit integers (1000000000000000000) but gives -1486618624 for a 32-bit integer. The same page shows that np.power(100, 100, dtype=np.int64) returns 0, which is incorrect, while dtype=np.float64 returns 1e+200. Because np.square returns the dtype of its input, the same fixed-size limits apply to it. If your values are large, pass dtype=np.float64 or start from a wider type. Plain Python integers do not have this problem because their size is flexible.

The result is not what I expected for a matrix

You are probably expecting A @ A. np.square is element-wise; use matrix multiplication or numpy.linalg.matrix_power for matrix squaring.

Garbage values appear in some positions

This happens when where is used without out. Positions where the condition is False are left uninitialized in a newly allocated array. Pass an out array that already holds the values you want to keep.

ImportError when importing numpy

Follow the official NumPy ImportError troubleshooting page linked from the install instructions.

Free alternatives

NumPy itself is free to install. These are the other ways the NumPy documentation shows to square values; all of them are element-wise on arrays except plain Python.

Option What the documentation says
x ** 2 The ** operator is shorthand for np.power on ndarrays.
np.power(x, 2) Raises each base in x1 to the corresponding power in x2, with broadcasting. Integers raised to a negative integer power raise a ValueError; negative values raised to a non-integral power return nan.
np.float_power(x, 2) Listed in the power documentation as the variant that promotes integers to float.
Plain Python int Python’s int has a flexible size and will not overflow, unlike fixed-size NumPy integer types.

FAQ

What is the numpy square root?

The inverse operation is np.sqrt, which takes the square root of each element. np.square and np.sqrt are separate functions; the reference lists sqrt and power as related functions. See the np.sqrt guide for syntax and edge cases.

Is np.square the same as x ** 2?

np.square computes element-wise x*x. On ndarrays the ** operator is shorthand for np.power, so x ** 2 goes through the power function. Both operate element by element.

How do I square a matrix?

Use matrix multiplication (A @ A) or numpy.linalg.matrix_power. np.square squares each entry individually.

What dtype does np.square return?

The same dtype as the input, per the NumPy reference. Pass dtype=np.float64 to compute in floating point.

Sources

Related reading on CASRAI: np.abs and np.linalg.norm.

Follow CASRAI

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

Ask CASRAI · free to try

Ask about NumPy Square: np.square Syntax, dtype and Overflow

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 →