Skip to content

Commit

Permalink
Merge pull request #23166 from oscarbenjamin/pr_derivative_110
Browse files Browse the repository at this point in the history
core/function: Fix regression in derivative (1.10 branch)
  • Loading branch information
oscarbenjamin committed Feb 25, 2022
2 parents 62bb95e + 67b2a9c commit 0d2c22e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 25 deletions.
53 changes: 28 additions & 25 deletions sympy/core/function.py
Expand Up @@ -47,7 +47,7 @@
from .parameters import global_parameters
from .rules import Transform
from .singleton import S
from .sympify import sympify
from .sympify import sympify, _sympify

from .sorting import default_sort_key, ordered
from sympy.utilities.exceptions import (sympy_deprecation_warning,
Expand Down Expand Up @@ -1276,12 +1276,36 @@ def __new__(cls, expr, *variables, **kwargs):
# derivative.
variable_count = []
array_likes = (tuple, list, Tuple)
integer_likes = (int, Integer)

from sympy.tensor.array import Array, NDimArray

for i, v in enumerate(variables):
if isinstance(v, integer_likes):
if isinstance(v, UndefinedFunction):
raise TypeError(
"cannot differentiate wrt "
"UndefinedFunction: %s" % v)

if isinstance(v, array_likes):
if len(v) == 0:
# Ignore empty tuples: Derivative(expr, ... , (), ... )
continue
if isinstance(v[0], array_likes):
# Derive by array: Derivative(expr, ... , [[x, y, z]], ... )
if len(v) == 1:
v = Array(v[0])
count = 1
else:
v, count = v
v = Array(v)
else:
v, count = v
if count == 0:
continue
variable_count.append(Tuple(v, count))
continue

v = _sympify(v)
if isinstance(v, Integer):
if i == 0:
raise ValueError("First variable cannot be a number: %i" % v)
count = v
Expand All @@ -1293,28 +1317,7 @@ def __new__(cls, expr, *variables, **kwargs):
else:
variable_count[-1] = Tuple(prev, count)
else:
if isinstance(v, array_likes):
if len(v) == 0:
# Ignore empty tuples: Derivative(expr, ... , (), ... )
continue
if isinstance(v[0], array_likes):
# Derive by array: Derivative(expr, ... , [[x, y, z]], ... )
if len(v) == 1:
v = Array(v[0])
count = 1
else:
v, count = v
v = Array(v)
else:
v, count = v
if count == 0:
continue
elif isinstance(v, UndefinedFunction):
raise TypeError(
"cannot differentiate wrt "
"UndefinedFunction: %s" % v)
else:
count = 1
count = 1
variable_count.append(Tuple(v, count))

# light evaluation of contiguous, identical
Expand Down
8 changes: 8 additions & 0 deletions sympy/core/tests/test_function.py
Expand Up @@ -777,6 +777,14 @@ def test_diff_wrt_not_allowed():
assert diff(exp(x*y), x*y, 0) == exp(x*y)


def test_diff_wrt_intlike():
class Two:
def __int__(self):
return 2

assert cos(x).diff(x, Two()) == -cos(x)


def test_klein_gordon_lagrangian():
m = Symbol('m')
phi = f(x, t)
Expand Down

0 comments on commit 0d2c22e

Please sign in to comment.