Skip to content

BUG: numpy.gradient fails when passing both varargs and axis parameters #29639

@mountaindust

Description

@mountaindust

Describe the issue:

A TypeError is raised on line 1253 when both a particular axis is requested and varargs is passed with length > 1. The implementation of gradient seems not to consider the case where a user might pass in spacing for each dimension AND want only a specific dimension of the gradient out. It is easy to reproduce this error by simply combining two of the examples given in the gradient documentation.

Reproduce the code example:

import numpy as np
dx = 2.
y = [1., 1.5, 3.5]
np.gradient(np.array([[1, 2, 6], [3, 4, 5]]), dx, y, axis=0)

Error message:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[6], line 1
----> 1 np.gradient(np.array([[1, 2, 6], [3, 4, 5]]), dx, y, axis=0)

File ~\miniforge3\Lib\site-packages\numpy\lib\_function_base_impl.py:1253, in gradient(f, axis, edge_order, *varargs)
   1251         dx[i] = diffx
   1252 else:
-> 1253     raise TypeError("invalid number of arguments")
   1255 if edge_order > 2:
   1256     raise ValueError("'edge_order' greater than 2 not supported")

TypeError: invalid number of arguments

Python and NumPy Versions:

2.3.0
3.12.10 | packaged by conda-forge | (main, Apr 10 2025, 22:08:16) [MSC v.1943 64 bit (AMD64)]

Runtime Environment:

No response

Context for the issue:

I need to calculate vorticity of a fluid velocity field in as efficient a manner as possible for a mathematics research code that I am developing at a large state institution. This means that I only need certain components of the gradient, and fluid velocity field comes from a rectilinear grid. So I need to be able to pass both arguments into numpy.gradient. Beyond that, calculating the gradient of a vector field is a typical operations for numerical work; the API for such a function should work as advertised. Also, this does not seem like something that would be too time consuming to fix.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions