Search code examples
numpyjupyter-notebookscipy-optimize

Jupyter notebook deprecation warning in finding the root of the determinant of a matrix


Given a matrix A, in which some of the elements are functions of x, find x such that det(A) = 0.

I started with a 5x5 diagonal matrix, shown in the code. The root function actually gave the right root (x = 1.562) but with

DeprecationWarning: Conversion of an array with ndim > 0 to a scalar is deprecated, and will error in future. Ensure you extract a single element from your array before performing this operation.

def test(x):
    A = np.zeros((5,5))
    for i in range(5):
        A[i,i] = x**2-4+x
    return np.linalg.det(A)

root(test, 3)

However, if we just want the determinant, running test(3) is totally fine. I have no idea how this warning comes out and how to avoid it. I'm guessing there might be something to do with the root finding function, but I'm not sure how exactly. I'm afraid when the size of the matrix becomes very large, it won't find the true root. Has anyone have experienced similar problems? Any advice will be appreciated.


Solution

  • If you look at the source code for root you will see that it calls _root_hybr if no method is provided. Going to _root_hybr we can see that there is this line:

    x0 = asarray(x0).flatten()
    

    This converts your input x0 which is 3 to an array, array([3]), so now your input to test is an array with ndim=1 rather than the scalar you provided. So when you compute x**2-4+x this is also an array of ndim=1 rather than the scalar you might expect. The warning is stating that setting an element of an array with an array with ndim>0 is deprecated, so it won't work in the future. To avoid the warning and the future error, within your function you need to convert x back to the scalar value your function expects which you can do with x = x.item().