'Fill in values of $x$ and $y$ in Jacobian

I wrote a function in Python to calculate the Jacobian for a set of two non-linear equations. How can I fill in values for $x$ and $y$? This is my code:

x= Symbol('x')
y= Symbol('y')

F = [3*x**2+2*y**2-25,2*x**2-y-15]

def jacobiaan(F):
    j11 = diff(F[0], x)
    j12 = diff(F[0],y)  
    j21 = diff(F[1],x)
    j22 = diff(F[1],y)
    jac = [[j11,j12],[j21,j22]]
    return jac

print(jacobiaan(F))


Solution 1:[1]

Your expressions are sitting in a list of lists. If you want to deal with them that way you either have to assign values before creating the list of after. To do it before, pass those values as parameters jacobiaan(F, xval, yval) and do something like j11 = diff(F[0], x).subs(x, xval). To do so afterwards you have to traverse the lists:

>>> lol = [[x, x + 1], [x + 2, x + 3]]
>>> [[i.subs(x, 1) for i in j] for j in lol]
[[1, 2], [3, 4]]

But it might be easier to just convert the list-of-lists to a Matrix and let it do the traversal:

>>> Matrix(lol).subs(x,1)
Matrix([
[1, 2],
[3, 4]])
>>> _.tolist()
[[1, 2], [3, 4]]

And easier still, to let SymPy compute the Jacobian:

>>> Matrix([x, x**2 + y]).jacobian((x, y))
Matrix([
[  1, 0],
[2*x, 1]])
>>> _.subs(x,2)
Matrix([
[1, 0],
[4, 1]])

With the final approach, you get the data into a SymPy object from the start.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 smichr