How do you rate the derivative in python?

I am a beginner in python. I recently learned about Sympy and its symbolic manipulation capabilities, in particular about differentiation. I try to do the following in the simplest way:

  • Define f (x, y) = x ^ 2 + xy ^ 2.
  • We differentiate f with respect to x. So f '(x, y) = 2x + xy ^ 2.
  • Estimate the derivative, for example, f '(1,1) = 2 + 1 = 3.

I know how to do 1 and 2. The problem is that when I try to evaluate the derivative in step 3, I get an error that python cannot calculate the derivative. Here is a minimal working example:

import sympy as sym
import math


def f(x,y):
    return x**2 + x*y**2


x, y = sym.symbols('x y')

def fprime(x,y):
    return sym.diff(f(x,y),x)

print(fprime(x,y)) #This works.

print(fprime(1,1)) 

I expect the last line to be printed 3. It does not print anything and says: "It is impossible to calculate the 1st derivative with respect to 1".

+3
3

. , subs, , , , . : lambdify, .

lambdify, sympy ( , ) ( , .., ). , sym.sin(x) np.sin(x). : , , , .

, sym.lambdify :

sym.lambdify(variable, function(variable), "numpy")

"numpy" - , sympy- . :

def f(x):
    return sym.cos(x)

def fprime(x):
    return sym.diff(f(x),x)

fprimeLambdified = sym.lambdify(x,f(x),"numpy")

fprime(x) -sym.sin(x), fprimeLambdified(x) -np.sin(x). "" / fprimeLambdified , "" / fprime, numpy sympy. , fprimelambdified(math.pi), , fprime(math.pi) .

sym.lambdify .

import sympy as sym
import math


def f(x,y):
    return x**2 + x*y**2


x, y = sym.symbols('x y')

def fprime(x,y):
    return sym.diff(f(x,y),x)

print(fprime(x,y)) #This works.

DerivativeOfF = sym.lambdify((x,y),fprime(x,y),"numpy")

print(DerivativeOfF(1,1))
0

fprime . , ( Sympy). , .subs :

>>> fprime(x, y).evalf(subs={x: 1, y: 1})
3.00000000000000

, fprime , fprime, . evalf :

>>> fprime = sym.diff(f(x,y),x)
>>> fprime.evalf(subs={x: 1, y: 1})
3.00000000000000
+4

When you call fprime (1,1) in the fprime (x, y) function, you call it like this: sym.diff (f (1,1), 1)

You must use different variables for x and the value of x

0
source

Source: https://habr.com/ru/post/1678261/


All Articles