Найти частную производную питон

Вычисление производной

Для вычисления производных будем использовать библиотеку SymPy. Это библиотека с открытым исходным кодом, полностью написанная на языке Python. Разрабатывается как система компьютерной алгебры.

Подключение SymPy

Вначале нам необходимо установить библиотеку. Для этого в терминале (командной строке) следует ввести команду: pip install sympy .

Для подключения библиотеки в коде на Python 3 следует использовать ключевое слово import .

Чтобы не писать перед всеми функциями sympy с точкой, подключу следующим образом:

Следует обратить внимание, что в SymPy объявлено множество классов и функций, имена которых могут пересекаться с названиями в других библиотеках. Например, если используете библиотеку math, то там также есть sin , cos , pi и другие.

Формула российских дорог

Например, возьмем функцию с двумя независимыми переменными, типа поверхности y=f(x, z). Воспользуемся формулой российских дорог: y=sin(x)+0,5·z.

Перед тем как взять производную этой функции в Python, надо объявить все переменные, которые будут использоваться в ней. Для этого следует воспользоваться функцией symbols . В качестве аргумента используем строку с перечисленными через запятую или пробел названиями переменных.

После этого берем частную производную в Python 3 с помощью функции diff . Первым аргументом пишем функцию, вторым – переменную, по которой будем её дифференцировать.

Читайте также:  Стили таблиц для php

Результат выводим с помощью print .

Дорога в горку

from sympy import * x, z = symbols('x z') print(diff(sin(x)+0.5*z, z)) 0.500000000000000

В результате получили 0.5. Частная производная по z положительна, следовательно, дорога в горку.

Дорога с колеёй

Теперь возьмём производную по x:

from sympy import * x, z = symbols('x z') print(diff(sin(x)+0.5*z, x)) cos(x)

Получили, что частная производная по x равна cos(x). Трактору на колею наплевать, ему важен только наклон горки.

В зависимости от задачи берем производную по нужному параметру.

В функции diff при необходимости, можно указать третьим параметром порядок дифференцирования. Так как мы вычисляли производную первого порядка, то его не указывали.

Источник

Derivatives in Python using SymPy

Derivatives With Python

How to calculate derivatives in Python? In this article, we’ll use the Python SymPy library to play around with derivatives.

What are derivatives?

Derivatives are the fundamental tools of Calculus. It is very useful for optimizing a loss function with gradient descent in Machine Learning is possible only because of derivatives.

Suppose we have a function y = f(x) which is dependent on x then the derivation of this function means the rate at which the value y of the function changes with the change in x.

This is by no means an article about the fundamentals of derivatives, it can’t be. Calculus is a different beast that requires special attention. I presume you have some background in calculus. This article is intended to demonstrate how we can differentiate a function using the Sympy library.

Solving Derivatives in Python using SymPy

Python SymPy library is created for symbolic mathematics. The SymPy project aims to become a full-featured computer algebra system (CAS) while keeping the code simple to understand. Let’s see how to calculate derivatives in Python using SymPy.

1. Install SymPy using PIP

SymPy has more uses than just calculating derivatives but as of now, we’ll focus on derivatives. Let’s use PIP to install SymPy module.

2. Solving a differential with SymPy diff()

For differentiation, SymPy provides us with the diff method to output the derivative of the function.

Let’s see how can we achieve this using SymPy diff() function.

#Importing sympy from sympy import * # create a "symbol" called x x = Symbol('x') #Define function f = x**2 #Calculating Derivative derivative_f = f.diff(x) derivative_f

Output Of The Above Function

Declaring a symbol is similar to saying that our function has a variable ‘x’ or simply the function depends on x.

3. Solving Derivatives in Python

SymPy has lambdify function to calculate the derivative of the function that accepts symbol and the function as argument. Let’s look at example of calculating derivative using SymPy lambdify function.

from sympy import * # create a "symbol" called x x = Symbol('x') #Define function f = x**2 f1 = lambdify(x, f) #passing x=2 to the function f1(2)

Basic Derivative Rules in Python SymPy

There are certain rules we can use to calculate the derivative of differentiable functions.

Some of the most encountered rules are:

Let’s dive into how can we actually use sympy to calculate derivatives as implied by the general differentiation rules.

1. Power Rule

Example, Function we have : f(x) = x⁵

It’s derivative will be : f'(x) = 5x (5-1) = 5x 4

import sympy as sym #Power rule x = sym.Symbol('x') f = x**5 derivative_f = f.diff(x) derivative_f

Power Rule Output

2. Product Rule

Let u(x) and v(x) be differentiable functions. Then the product of the functions u(x)v(x) is also differentiable.

import sympy as sym #Product Rule x = sym.Symbol('x') f = sym.exp(x)*sym.cos(x) derivative_f = f.diff(x) derivative_f

Product Rule Output solve derivatives in Python

3. Chain Rule

The chain rule calculate the derivative of a composition of functions.

  • Say, we have a function h(x) = f( g(x) )
  • Then according to chain rule: h′(x) = f ′(g(x)) g′(x)
  • Example: f(x) = cos(x**2)

This process can be extended for quotient rule also. It must be obvious by now that only the function is changing while the application process remains the same, the remaining is taken care of by the library itself.

import sympy as sym #Chain Rule x = sym.Symbol('x') f = sym.cos(x**2) derivative_f = f.diff(x) derivative_f

Chain Rule Output

Python Partial Derivative using SymPy

The examples we saw above just had one variable. But we are more likely to encounter functions having more than one variables. Such derivatives are generally referred to as partial derivative.

A partial derivative of a multivariable function is a derivative with respect to one variable with all other variables held constant.

Example: f(x,y) = x 4 + x * y 4

Let’s partially differentiate the above derivatives in Python w.r.t x.

import sympy as sym #Derivatives of multivariable function x , y = sym.symbols('x y') f = x**4+x*y**4 #Differentiating partially w.r.t x derivative_f = f.diff(x) derivative_f

Partial Differentiation W R T X solve derivatives in Python

We use symbols method when the number of variables is more than 1. Now, differentiate the derivatives in Python partially w.r.t y

import sympy as sym #Derivatives of multivariable function x , y = sym.symbols('x y') f = x**4+x*y**4 #Differentiating partially w.r.t y derivative_f = f.diff(y) derivative_f

Partial Differentiation W R T Y

The code is exactly similar but now y is passed as input argument in diff method.

We can choose to partially differentiate function first w.r.t x and then y.

import sympy as sym #Derivatives of multivariable function x , y = sym.symbols('x y') f = x**4+x*y**4 #Differentiating partially w.r.t x and y derivative_f = f.diff(x,y) derivative_f

Partial Differentiation W R T X And Y solve derivatives in Python

Summary

This article by no means was a course about derivatives or how can we solve derivatives in Python but an article about how can we leverage python SymPy packages to perform differentiation on functions. Derivatives are awesome and you should definitely get the idea behind it as they play a crucial role in Machine learning and beyond.

What’s Next?

Resources

Источник

Calculate Partial Derivatives in Python Using Sympy

Calculate Partial Derivatives in Python Using Sympy

A partial derivative is a function’s derivative that has two or more other variables instead of one variable. Because the function is dependant on several variables, the derivative converts into the partial derivative.

For example, where a function f(b,c) exists, the function depends on the two variables, b and c , where both of these variables are independent of each other. The function, however, is partially dependant on both b and c . Therefore, to calculate the derivative of f , this derivative will be referred to as the partial derivative . If you differentiate the f function with reference to b, you will use c as the constant. Otherwise, if you differentiate f regarding c, you will take b as the constant instead.

In Python, the Sympy module is used to calculate the partial derivative in a mathematical function. This module uses symbols to perform all different kinds of computations. It can also be used to solve equations, simplify expressions, compute derivatives and limits, and other computations.

Sympy needs to be manually installed before it can be used. Therefore, cd to your computer terminal and run the following command to install the sympy package.

To use sympy to compute a partial derivative, you first need to import the sympy package from symbols.

The computer evaluates the computation of values differently from how they are put down on a piece of paper. Therefore, symbols here will be in the form of variables that hold the real values to be evaluated. Thus, during the computation, the computer manipulates the variable to the value it is attached to.

Now, let’s use the following example to derive the partial derivative of the function.

f(a, b, c) = 5ab - acos(c)+ a^2 + c^8b  part_deriv(function = f, variable = a) 

The expected output after differentiating the function to its partial derivative is 2*a + 5*b — cos(c) .

To evaluate the partial derivative of the function above, we differentiate this function in respect to a while b and c will be the constants.

from sympy import symbols, cos, diff  a, b, c = symbols('a b c', real=True) f = 5*a*b - a*cos(c) + a**2 + c**8*b  #differntiating function f in respect to a print(diff(f, a)) 

Источник

Оцените статью