Skip to content

Commit

Permalink
BUG: Avoid inplace modification of input array in newton
Browse files Browse the repository at this point in the history
optimize.newton previously changes the users input array when
performing calculations. This PR changes this to perform an explicit
copy of the array before any inplace modifications are performed.
  • Loading branch information
Kai-Striega committed Mar 29, 2019
1 parent d44296c commit 655e9ed
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
11 changes: 10 additions & 1 deletion scipy/optimize/tests/test_zeros.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@

from numpy.testing import (assert_warns, assert_,
assert_allclose,
assert_equal)
assert_equal,
assert_array_equal)
import numpy as np
from numpy import finfo, power, nan, isclose

Expand Down Expand Up @@ -407,6 +408,14 @@ def test_deriv_zero_warning(self):
assert_warns(RuntimeWarning, zeros.newton, func, 0.0, dfunc)


def test_newton_does_not_modify_x0(self):
# https://github.com/scipy/scipy/issues/9964
x0 = np.array([0.1, 3])
x0_copy = x0.copy() # Copy to test for equality.
newton(np.sin, x0, np.cos)
assert_array_equal(x0, x0_copy)


def test_gh_5555():
root = 0.1

Expand Down
6 changes: 4 additions & 2 deletions scipy/optimize/zeros.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,11 +359,13 @@ def _array_newton(func, x0, fprime, args, tol, maxiter, fprime2, full_output):
Do not use this method directly. This method is called from `newton`
when ``np.size(x0) > 1`` is ``True``. For docstring, see `newton`.
"""
# Explicitly copy `x0` as `p` will be modified inplace, but, the
# user's array should not be altered.
try:
p = np.asarray(x0, dtype=float)
p = np.array(x0, copy=True, dtype=float)
except TypeError:
# can't convert complex to float
p = np.asarray(x0)
p = np.array(x0, copy=True)

failures = np.ones_like(p, dtype=bool)
nz_der = np.ones_like(failures)
Expand Down

0 comments on commit 655e9ed

Please sign in to comment.