AGENDA FOR THIS TUTORIAL¶

  1. WHAT IS A FUNCTION and MATHS OVERVIEW?
  2. COMMON MATHEMATICAL OPERATIONS AND FUNCTIONS IN PYTHON
  3. COMMON MATHEMATICAL FUNCTIONS AVAILABLE IN PYTHON'S STANDARD LIBRARY
  4. INTRO TO SymPy LIBRARY
  5. LEARN TO FIND LIMITS OF FUNCTIONS
  6. CALCULATE DERIVATIVES OF FUNCTIONS
  7. CALCULATE INTEGRALS OF FUNCTIONS

WHAT IS A FUNCTION?¶

Functions are the fundamental part of the calculus in mathematics.

The functions are the special types of relations.

A function is a mapping between an input set and an output set.

The special condition of a function is that an element of the input set is related to exactly one element of the output set.

img

Here, an element of the output set is the square of an element from the input set.

Graphically¶

$\Large f(x) = x^2$
where, x is the independent variable

img01

Domain and Range of a Function¶

  • The domain of a function is the set of input values that the independent variable can validly assume.

(Values that we can take)

  • The output set of a function is called the range.(Possible values that we can get)

img03

Domain: $[−5,∞)$
Range: $(−∞,5]$

EXERCISE: FINDING DOMAIN AND RANGE FROM A GRAPH¶

img034

COMMON MATHEMATICAL OPERATORS & FUNCTIONS IN PYTHON¶

MATH OPERATIONS¶

In [13]:
a, b = 3, 4

print("ADDITION OF TWO NUMBERS:")
print(a+b)
ADDITION OF TWO NUMBERS:
7
In [5]:
print("SUBTRACTION OF TWO NUMBERS:")
print(a-b)
ADDITION OF TWO NUMBERS:
-1
In [6]:
print("MULTIPLICATION OF TWO NUMBERS:")
print(a*b)
MULTIPLICATION OF TWO NUMBERS:
-1
In [8]:
print("TRUE DIVISION OF TWO NUMBERS:")
print(a/b)
TRUE DIVISION OF TWO NUMBERS:
0.75
In [12]:
print("FLOOR DIVISION OF TWO NUMBERS:")
print(a//b)
FLOOR DIVISION OF TWO NUMBERS:
0
In [10]:
print("REMAINDER OF TWO NUMBERS:")
print(a%b)
REMAINDER OF TWO NUMBERS:
3
In [11]:
print("POWER OF TWO NUMBERS:")
print(a**b)
POWER OF TWO NUMBERS:
81

LOGIC TESTS¶

In [16]:
a,b = 5, 3

print("Check a is greater than b")
print(a > b)
Check a is greater than b
True
In [17]:
print("Check a is greater than or equal to b")
print(a >= b)
Check a is greater than or equal to b
True
In [18]:
print("Check a is equal to b")
print(a == b)
Check a is equal to b
False
In [19]:
print("Check a is not equal to b")
print( a != b)
Check a is not equal to b
True
In [20]:
print("Check a is less than b")
print(a < b)
Check a is less than b
False
In [21]:
print("Check a is less than or equal to b")
print(a <= b)
Check a is less than or equal to b
False

MATH MODULE¶

Math module provides functions to deal with both basic operations such as addition(+), subtraction(-), multiplication(*), division(/) and advance operations like trigonometric, logarithmic, exponential functions.

In [37]:
import math

## constants
print("Euler's Number:", end = " ")
print(math.e)  # euler's number

print("PI:", end = " ")
print(math.pi)  # pi

print("Tau (Ratio of Circumference to the radius of a circle):", end = " ")
print(math.tau) # tau

print("Infinity (never ending):", end = " ")
print(math.inf, end = " ")   # positive infinity
print(-math.inf)  # negative infinity

print("NaN (Not a Number):", end = " " )
print(math.nan) # floating point Not a Number value
Euler's Number: 2.718281828459045
PI: 3.141592653589793
Tau (Ratio of Circumference to the radius of a circle): 6.283185307179586
Infinity (never ending): inf -inf
NaN (Not a Number): nan

NUMERIC FUNCTIONS¶

In [39]:
import math

a = 2.3
b = -1.3
c = 3

print ("The ceil of 2.3 is : ", end="")
print(math.ceil(a))

print ("The ceil of -1.3 is : ", end="")
print(math.ceil(b))

print ("The ceil of 3 is : ", end="")
print(math.ceil(c))
The ceil of 2.3 is : 3
The ceil of -1.3 is : -1
The ceil of 3 is : 3

It is equivalent to the Least integer function (LIF) in mathematics.

img12

In [41]:
import math

a = 2.3
b = -1.3
c = 3

print ("The floor of 2.3 is : ", end="")
print(math.floor(a))

print ("The floor of -1.3 is : ", end="")
print(math.floor(b))

print ("The floor of 3 is : ", end="")
print(math.floor(c))
The floor of 2.3 is : 2
The floor of -1.3 is : -2
The floor of 3 is : 3

It is equivalent to Greatest integer function (GIF) in mathematics. img123

In [42]:
import math
 
a = -10
b = 10

# absolute value or modulus function
print ("The absolute value of -10 is : ", end="")
print (math.fabs(a))

print ("The absolute value of 10 is : ", end="")
print (math.fabs(b))
The absolute value of -10 is : 10.0
The absolute value of 10 is : 10.0

img234

In [44]:
import math
 
a = 4
b = -3
c = 0.00
 
# exp() values
print ("The exp() value of 4 is : ", end="")
print (math.exp(a))

print ("The exp() value of -3 is : ", end="")
print (math.exp(b))

print ("The exp() value of 0.00 is : ", end="")
print (math.exp(c))
The exp() value of 4 is : 54.598150033144236
The exp() value of -3 is : 0.049787068367863944
The exp() value of 0.00 is : 1.0

img00

In [45]:
import math

# log of 2,3
print ("The value of log 2 with base 3 is : ", end="")
print (math.log(2,3))
 
# returning the log2 of 16
print ("The value of log2 of 16 is : ", end="")
print (math.log2(16))
    
# returning the log10 of 10000
print ("The value of log10 of 10000 is : ", end="")
print (math.log10(10000))
The value of log 2 with base 3 is : 0.6309297535714574
The value of log2 of 16 is : 4.0
The value of log10 of 10000 is : 4.0

The function $\large y=log_{b}x$ is the inverse function of the exponential function $\large y=b^x$

img

When no base is written, assume that the log is base 10

img45

Graph of $log_{2}x$

img1234

In [48]:
import math
 
# print the square root of 0
print ("The square root of 0 is : ", end="")
print(math.sqrt(0))
 
# print the square root of 4
print ("The square root of 4 is : ", end="")
print(math.sqrt(4))
 
# print the square root of 3.5
print ("The square root of 3.5 is : ", end="")
print(math.sqrt(3.5))
The square root of 0 is : 0.0
The square root of 4 is : 2.0
The square root of 3.5 is : 1.8708286933869707

img890

In [49]:
import math
 
a = math.pi/6
 
# returning the value of sine of pi/6
print ("The value of sine of pi/6 is : ", end="")
print (math.sin(a))  # value passed must be radians
 
# returning the value of cosine of pi/6
print ("The value of cosine of pi/6 is : ", end="")
print (math.cos(a))
 
# returning the value of tangent of pi/6
print ("The value of tangent of pi/6 is : ", end="")
print (math.tan(a))
The value of sine of pi/6 is : 0.49999999999999994
The value of cosine of pi/6 is : 0.8660254037844387
The value of tangent of pi/6 is : 0.5773502691896257

img90

In [50]:
import math
 
a = math.pi/6
b = 30
 
# returning the converted value from radians to degrees
print ("The converted value from radians to degrees is : ", end="")
print (math.degrees(a))
 
# returning the converted value from degrees to radians
print ("The converted value from degrees to radians is : ", end="")
print (math.radians(b))
The converted value from radians to degrees is : 29.999999999999996
The converted value from degrees to radians is : 0.5235987755982988

imag12345

In [53]:
import math
 
# initializing argument
gamma_var = 5
 
# Printing the gamma value.
print ("The gamma value of the given argument is : " + str(math.gamma(gamma_var)))
The gamma value of the given argument is : 24.0

img098

The (complete) gamma function $ \Gamma(n)$ is defined to be an extension of the factorial to complex and real number arguments.

img098

It is often used in probability and statistics, as it shows up in the normalizing constants of important probability distributions such as the Chi-square and the Gamma.

img

Graph of Gamma Function¶

img788

SymPY Module¶

One drawback of all these functions is that they’re not suitable for working with symbolic expressions.

If we want to manipulate a mathematical expression involving symbols, we have to start using the equivalent functions defined by SymPy.

SymPy is a Python library for symbolic mathematics

In [57]:
!pip install sympy --user
Requirement already satisfied: sympy in c:\python311\lib\site-packages (1.12)
Requirement already satisfied: mpmath>=0.19 in c:\python311\lib\site-packages (from sympy) (1.3.0)
In [58]:
import sympy

sympy.sin(math.pi/2)
Out[58]:
$\displaystyle 1.0$
In [59]:
from sympy import Symbol

theta = Symbol('theta')

# using math
print(math.sin(theta) + math.sin(theta))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[59], line 6
      3 theta = Symbol('theta')
      5 # using math
----> 6 print(math.sin(theta) + math.sin(theta))

File C:\Python311\Lib\site-packages\sympy\core\expr.py:351, in Expr.__float__(self)
    349 if result.is_number and result.as_real_imag()[1]:
    350     raise TypeError("Cannot convert complex to float")
--> 351 raise TypeError("Cannot convert expression to float")

TypeError: Cannot convert expression to float
In [60]:
# using sympy
print(sympy.sin(theta) + sympy.sin(theta))
2*sin(theta)
In [62]:
from sympy import Symbol

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

z = (x + y) + (x-y)
print("Value of z is: ", z)
Value of z is:  2*x
In [63]:
from sympy import sin, solve, Symbol
u = Symbol('u')
t = Symbol('t')
g = Symbol('g')

theta = Symbol('theta')

solve(u*sin(theta)-g*t, t)
Out[63]:
[u*sin(theta)/g]

Assumptions in SymPy¶

In [64]:
from sympy import Symbol

x = Symbol('x')

if (x + 5) > 0:
    print("Do something")
else:
    print("Do something else")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[64], line 5
      1 from sympy import Symbol
      3 x = Symbol('x')
----> 5 if (x + 5) > 0:
      6     print("Do something")
      7 else:

File C:\Python311\Lib\site-packages\sympy\core\relational.py:510, in Relational.__bool__(self)
    509 def __bool__(self):
--> 510     raise TypeError("cannot determine truth value of Relational")

TypeError: cannot determine truth value of Relational

Error thrown because SymPy doesn't know anything about the sign if x, it can't deduce whether x+5 is greather than 0, so it displays an error.

But basic math tells us that if x is positive, x + 5 will always be positive, and if x is negative, it will be positive only in certain cases.

So if we create a Symbol object specifying positive=True, we tell SymPy to assume only positive values.

Now it knows for sure that x + 5 is definitely greater than 0

In [69]:
from sympy import Symbol

x = Symbol('x', positive=True)

if (x + 5) > 0:
    print("Do something")
else:
    print("Do something else")
Do something

If we’d instead specified negative=True, we could get the same error as in the first case.

Just as we can declare a symbol as positive and negative, it’s also possible to specify it as real, integer, complex, imaginary, and so on.

These declarations are referred to as assumptions in SymPy.

LIMIT OF FUNCTIONS¶

A common task in calculus is finding the limiting value (or simply the limit) of the function, when the variable’s value is assumed to approach a certain value.

Consider a function $\Large f(x) = \frac{1}{x}$

img098

As the value of x increases, the value of f(x) approaches 0. Using the limit notation, we'd write this as:

img789

In [72]:
from sympy import Limit, Symbol, S

x = Symbol('x')

Limit(1/x, x, S.Infinity) # unevaluated object
Out[72]:
$\displaystyle \lim_{x \to \infty} \frac{1}{x}$

oo denotes positive infinity and the dir='-' symbol specifying that we are approaching the limit from the negative side.

In [73]:
## to find the value of the limit
## use doit() method

l = Limit(1/x, x, S.Infinity)
l.doit()
Out[73]:
$\displaystyle 0$

By default, the limit is found from a positive direction, unless the value at which the limit is to be calculated is positive or negative infinity

In [76]:
Limit(1/x, x, 0, dir='-')
Out[76]:
$\displaystyle \lim_{x \to 0^-} \frac{1}{x}$
In [77]:
Limit(1/x, x, 0, dir='-').doit()
Out[77]:
$\displaystyle -\infty$
In [78]:
Limit(1/x, x, 0, dir='+')
Out[78]:
$\displaystyle \lim_{x \to 0^+} \frac{1}{x}$
In [79]:
Limit(1/x, x, 0, dir='+').doit()
Out[79]:
$\displaystyle \infty$

Indeterminate Forms¶

The indeterminate form is a Mathematical expression that means that we cannot be able to determine the original value even after the substitution of the limits.

Indeterminate forms are: img68

The Limit class also handles functions with limits of indeterminate forms automatically

In [82]:
from sympy import Symbol, sin

Limit(sin(x)/x, x, 0)  # 0/0 form
Out[82]:
$\displaystyle \lim_{x \to 0^+}\left(\frac{\sin{\left(x \right)}}{x}\right)$
In [81]:
Limit(sin(x)/x, x, 0).doit()
Out[81]:
$\displaystyle 1$

You have very likely used L’Hospital’s rule to find such limits, but as we see here, the Limit class takes care of this for us.

Futher Reading: https://tutorial.math.lamar.edu/classes/calci/lhospitalsrule.aspx

EXERCISE ON LIMITS¶

Solve:¶

$\large 1. \lim_{x \to 2} (8 - 3x + 12x^2)$

$\large 2. \lim_{t \to -3} \frac{6 + 4t}{t^2 + 1}$

$\large 3. \lim_{x \to -5} \frac{x^2 - 25}{x^2 + 2x - 15}$

$\large 4. \lim_{z \to -4} \frac{\sqrt z - 2}{z - 4}$

$\large 5. \lim_{t \to -1} \frac{t + 1}{|t+1|}$

For more questions to practice: https://tutorial.math.lamar.edu/problems/calci/computinglimits.aspx

For Latex Guide: https://www.math-linux.com/latex-26/faq/latex-faq/article/latex-derivatives-limits-sums-products-and-integrals

In [110]:
# Q1
from sympy import Limit, Symbol, S

x = Symbol('x')
Limit((8-3*x+12*x**2), x, 2).doit()
Out[110]:
$\displaystyle 50$
In [98]:
# Q2
from sympy import Limit, Symbol, S

t = Symbol('t')
Limit((6+4*t)/(t**2 + 1), t, -3).doit()
Out[98]:
$\displaystyle - \frac{3}{5}$
In [99]:
# Q3
from sympy import Limit, Symbol, S

x = Symbol('x')
Limit((x**2 - 25)/(x**2 + 2*x - 15), x, -5).doit()
Out[99]:
$\displaystyle \frac{5}{4}$
In [114]:
# Q4
from sympy import Limit, Symbol, S

z = Symbol('z')
Limit((z**(0.5) - 2)/(z - 4), z, 4).doit()
Out[114]:
$\displaystyle \frac{1}{4}$
In [120]:
# Q5
from sympy import Limit, Symbol, S

t = Symbol('t')

# left hand limit
LHL = Limit((t+1)/(abs(t+1)), t, -1, dir = '-').doit()

# right hand limit
RHL = Limit((t+1)/(abs(t+1)), t, -1, dir = '+').doit()

if LHL == RHL:
    print("Limit exists and value is: ", LHL)
else:
    print("Left Hand Limit is: ", LHL)
    print("Right Hand Limit is: ", RHL)
    print("Since LHL not equal to RHL")
    print("Limits does not exists")
Left Hand Limit is:  -1
Right Hand Limit is:  1
Since LHL not equal to RHL
Limits does not exists

Continuity of a Function¶

The term 'continuity' is derived from the word continuous, which means an endless or unbroken path.

A real function $\large f(x)$ can be considered as continuous at a point say, $\large x = a$, if the function $\large f(x)$ is approaching to $a$ is $\large f(a)$

img456

Further

img090


img908

Discontinuity¶

img890

QUESTION 01:¶

Check the continuity of a given function at x = 0:

$\large f(x) = 5x - 3$

In [143]:
# Check the continuity of the function at x = 0
from sympy import Limit, Symbol, S

x = Symbol('x')
f = 5*x - 3
c = 0

# AT x = 0
v = f.evalf(subs = {x: 0})

# left hand limit
LHL = Limit(f, x, 0, dir = '-').doit()

# Right hand limit
RHL = Limit(f, x, 0, dir = '+').doit()

if LHL == RHL == v:
    print("Given function is continuous at x = ", c)
elif LHL != RHL:
    print("Given function is discontinuous at x = ", c)
    print("Type of Discontinuity is: Jump Discontinuity")
elif LHL == RHL:
    print("Given function is discontinuous at x = ", c)
    print("Type of Discontinuity is: Removable Discontinuity")
elif (RHL == math.inf) and (LHL == -math.inf):
    print("Given function is discontinuous at x = ", c)
    print("Type of Discontinuity is: Infinite Discontinuity")
Given function is continuous at x =  0

QUESTION 02:¶

Check the continuity of a given function at x = 2:¶

$\large f(x) = \frac {1}{x - 2}$

In [148]:
# Check the continuity of the function at x = 2
from sympy import Limit, Symbol, S

x = Symbol('x')
f = 1/(x-2)
c = 2

# AT x = c
v = f.evalf(subs = {x: c})

# left hand limit
LHL = Limit(f, x, c, dir = '-').doit()

# Right hand limit
RHL = Limit(f, x, c, dir = '+').doit()

if LHL == RHL == v:
    print("Given function is continuous at x = ", c)
    
elif (RHL == math.inf) and (LHL == -math.inf):
    print("Given function is discontinuous at x = ", c)
    print("Type of Discontinuity is: Infinite Discontinuity")

elif LHL == RHL:
    print("Given function is discontinuous at x = ", c)
    print("Type of Discontinuity is: Removable Discontinuity")
    
elif LHL != RHL:
    print("Given function is discontinuous at x = ", c)
    print("Type of Discontinuity is: Jump Discontinuity")
Given function is discontinuous at x =  2
Type of Discontinuity is: Infinite Discontinuity

EXERCISE ON CONTINUITY¶

Check the continuity of the function given below:¶

$\large 1. f(x) = (8 - 3x + 12x^2)$ at x = 3

$\large 2. f(x) = \frac{6 + 4t}{t^2 + 1}$ at t = -1

$\large 3. f(x) = \frac{x^2 - 25}{x^2 + 2x - 15}$ at x = 3 and -5

$\large 4. f(x) = \frac{\sqrt z - 2}{z - 4}$ at z = 3

$\large 5. f(x) = \frac{t + 1}{|t+1|}$ at t = -1

Continuous Compound Interest¶

Say you have deposited Rs. 1000 in a bank. This deposit is the principal, which pays you interest -- in this case, interest of 100 % that compounds n times yearly for 1 year.

The amount you will get at the end of 1 year is given by

$\Huge A = ( 1 + \frac{1}{n})^n$

The prominent mathematician James Bernoulli discovered that as the value of n increases, the term $(1 + 1/n)^n$ approaches the value of $e$ — the constant that we can verify by finding the limit of the function:

$\Huge e = \lim_{n \to \infty} ( 1 + \frac{1}{n})^n$
In [151]:
# lets find out using python
from sympy import Limit, Symbol, S

n = Symbol('n')
l = Limit((1+1/n)**n, n, S.Infinity)
l
Out[151]:
$\displaystyle \lim_{n \to \infty} \left(1 + \frac{1}{n}\right)^{n}$
In [152]:
l.doit()
Out[152]:
$\displaystyle e$

For any principal amount p,
any rate r, and
any number of years t,

the compound interest is calculated using the formula:

$\Huge A = P( 1 + \frac{r}{n})^{nt}$
In [154]:
from sympy import Symbol, Limit, S

p = Symbol('p', positive = True)
r = Symbol('r', positive = True)
t = Symbol('t', positive = True)

l = Limit(p*(1+r/n)**(n*t), n, S.Infinity)
l
Out[154]:
$\displaystyle \lim_{n \to \infty}\left(p \left(1 + \frac{r}{n}\right)^{n t}\right)$
In [155]:
l.doit()
Out[155]:
$\displaystyle p e^{r t}$

Instantaneous Rate of Change¶

Consider a car moving along a road. It accelerates uniformly such that the distance traveled, S, is given by the function

$S(t) = 5t^2 + 2t + 8$

In this function, the independent variable is t, which represents the time elapsed since the car started moving

If we measure the distance traveled in time $t_1$ and time $t_2$ such that $t_2$ > $t_1$, then we can calculate the distance moved by the car in 1 unit of time using the expression

$\Huge \frac{S(t_{2}) - S(t_{1})}{t_{2} - t_{1}}$

This is also referred to as the average rate of change of the function $S(t)$ with respect to the variable t, or in other words, the average speed.

If we write the $\large t_{2}$ as $\large t_{1} + \delta_{t}$ -- where $\delta_{t}$ is the difference between $t_{2}$ and $t_{1}$ in units of time -- we can rewrite the expression for the average speed as

$\Huge \frac{S(t_{1} + \delta_{t}) - S(t_{1})}{\delta_{t}}$
This expression is also a function with $t_{1}$ as the variable.

Now, if we further assume $\delta_{t}$ to be really small, such that it approached 0, we can use limit notation to write this as

$\Huge \lim_{\delta_{t} \to 0} \frac{S(t_{1} + \delta_{t}) - S(t_{1})}{\delta_{t}}$
In [161]:
## let's evaluate the above limit

from sympy import Symbol, Limit

t = Symbol('t')
St = 5*t**2 + 2*t + 8

t1 = Symbol('t1')
delta_t = Symbol('delta_t')

St1 = St.subs({t: t1})
St1_delta = St.subs({t: t1 + delta_t})

l = Limit((St1_delta - St1)/ delta_t, delta_t, 0)
l
Out[161]:
$\displaystyle \lim_{\delta_{t} \to 0^+}\left(\frac{2 \delta_{t} - 5 t_{1}^{2} + 5 \left(\delta_{t} + t_{1}\right)^{2}}{\delta_{t}}\right)$
In [160]:
l.doit()
Out[160]:
$\displaystyle 10 t_{1} + 2$

This limit we calculated here is referred to as the derivative of a function, and we can calculate it directly using SymPy's Derivative class.

Finding the Derivative of Functions¶

In very simple words, the derivative of a function $f(x)$ represents its rate of change and is denoted by either $f'(x)$ or $\frac{df}{dx}$.

Let’s first look at its definition and a pictorial illustration of the derivative.

img

In [163]:
from sympy import Symbol, Derivative

t = Symbol('t')
St = 5*t**2 + 2*t + 8
d = Derivative(St, t)
d
Out[163]:
$\displaystyle \frac{d}{d t} \left(5 t^{2} + 2 t + 8\right)$
In [164]:
d.doit()
Out[164]:
$\displaystyle 10 t + 2$
In [165]:
d.doit().subs({t:t1})  # derivative at t = t1
Out[165]:
$\displaystyle 10 t_{1} + 2$
In [166]:
d.doit().subs({t:1})  # derivative at t = 1
Out[166]:
$\displaystyle 12$

Find the derivative of given function below:¶

$\large f(x) = (x^5 + x^3 + x)*(x^4 + x)$

In [168]:
from sympy import Derivative, Symbol

x = Symbol('x')
f = (x**5 + x**3 + x)*(x**4 + x)
Derivative(f,x).doit()
Out[168]:
$\displaystyle \left(4 x^{3} + 1\right) \left(x^{5} + x^{3} + x\right) + \left(x^{4} + x\right) \left(5 x^{4} + 3 x^{2} + 1\right)$

Derivative Calculator¶

In [177]:
"""
DERIVATIVE CALCULATOR
"""

from sympy import Symbol, Derivative, sympify, pprint
from sympy.core.sympify import SympifyError

def derivative(f, var):
    var = Symbol(var)
    d = Derivative(f, var).doit()
    pprint(d)

if __name__ == '__main__':
    f = input('Enter a function: ')
    var = input('Enter the variable to differentiate with respect to: ')
    try:
        f = sympify(f) # convert the input function into a SymPy object
    except SympfiyError:
        print("invalid input")
    else:
        derivative(f, var)
Enter a function: 2*x**2 + y**2
Enter the variable to differentiate with respect to: x
4⋅x

EXERCISE ON DERIVATIVES¶

FInd the first order derivatives for the following functions:¶

$\large 1. f(x) = (8 - 3x + 12x^2)$

$\large 2. f(x) = \frac{6 + 4t}{t^2 + 1}$

$\large 3. f(x) = \frac{x^2 - 25}{x^2 + 2x - 15}$

$\large 4. f(x) = \frac{\sqrt z - 2}{z - 4}$


Calculating Partial Derivatives¶

A Partial Derivative is a derivative where we hold some variables constant.

img

Example: A function for a surface that depends on two variables x and y.

  • When we find the slope in the x direction (while keeping y fixed) we have found a partial derivative.

    $\large \frac{\partial f(x,y)}{\partial x}$
  • Or we can find the slope in the y direction (while keeping x fixed).

    $\large \frac{\partial f(x,y)}{\partial y}$
In [187]:
from sympy import Derivative, Symbol

x = Symbol('x')
y = Symbol('y')
f = 2*(x**2)*y + x*y**2
Derivative(f,x).doit()
Out[187]:
$\displaystyle 4 x y + y^{2}$
In [188]:
from sympy import Derivative, Symbol

x = Symbol('x')
y = Symbol('y')
f = 2*(x**2)*y + x*y**2
Derivative(f,y).doit()
Out[188]:
$\displaystyle 2 x^{2} + 2 x y$

EXERCISE ON PARTIAL DERIVATIVES¶

FInd the first order partial derivatives for the following functions:¶

$\large 1. f(x,y) = x^4 + 6\sqrt y - 10 $

$\large 2. f(x,y,z) = x^2y - 10x^2z^3 + 43x - 7tan(4y)$

$\large 3. f(s,t) = t^7ln(s^2)+ \frac{9}{t^3} - \sqrt(s^4)$

$\large 4. f(x) = cos(\frac{4}{x})e^{x^2y-5y^3}$


HIGHER-ORDER DERIVATIVES AND FINDING THE MAXIMA AND MINIMA¶

Consider the function $\large f(x) = x^5 - 30x^3 + 50x$, defined on the domain [-5,5].

img

  • The points B and C are referred to as a local minimum and local maximum
  • While the points A and D are the global maximum and global minimum
  • The term extremum (plural extrema) refers to the points where the functions attains a local or global maximum or minimum.
  • If x is an extremum of the function f(x), then the first-order derivative of f at x, denotes f'(x), must vanish (zero).
  • This property shows that a good way to find possible extrema is to try to solve the equation $f'(x) = 0$.
  • Such solutions are called critical points of the functions.
In [197]:
from sympy import Symbol, solve, Derivative

x = Symbol('x')
f = x**5 - 30*x**3 + 50*x
d1 = Derivative(f,x).doit()
d1
Out[197]:
$\displaystyle 5 x^{4} - 90 x^{2} + 50$
In [198]:
critical_points = solve(d1)
critical_points
Out[198]:
[-sqrt(9 - sqrt(71)),
 sqrt(9 - sqrt(71)),
 -sqrt(sqrt(71) + 9),
 sqrt(sqrt(71) + 9)]
In [194]:
A = critical_points[2] # global maxima
B = critical_points[0] # local minima
C = critical_points[1] # local maxima
D = critical_points[3] # global minima
In [196]:
## second derivative
d2 = Derivative(f,x,2).doit()
d2
Out[196]:
$\displaystyle 20 x \left(x^{2} - 9\right)$
In [199]:
# evaluate second derivative by putting x = B
d2.subs({x:B}).evalf()
Out[199]:
$\displaystyle 127.661060789073$
In [200]:
# evaluate second derivative by putting x = C
d2.subs({x:C}).evalf()
Out[200]:
$\displaystyle -127.661060789073$
In [201]:
# evaluate second derivative by putting x = A
d2.subs({x:A}).evalf()
Out[201]:
$\displaystyle -703.493179468151$
In [202]:
# evaluate second derivative by putting x = D
d2.subs({x:D}).evalf()
Out[202]:
$\displaystyle 703.493179468151$

Evaluating the second derivative test at the critical points tells us that the points A and C are local maxima and the points B and D are local minima.

The global maximum and minimum of f(x) on the interval [–5, 5] is attained either at a critical point x or at one of the endpoints of the domain (x = –5 and x = 5).

To find the global maximum, we must compute the value of f(x) at the points A, C, –5, and 5. Among these points, the place where f(x) has the largest value must be the global maximum.

In [213]:
x_min = -5
x_max = 5

f.subs({x:A}).evalf()
Out[213]:
$\displaystyle 705.959460380365$
In [214]:
f.subs({x:C}).evalf()
Out[214]:
$\displaystyle 25.0846626340294$
In [215]:
f.subs({x:x_min}).evalf()
Out[215]:
$\displaystyle 375.0$
In [216]:
f.subs({x:x_max}).evalf()
Out[216]:
$\displaystyle -375.0$

Point A turns out be the global maximum¶

To determine the global minimum, we must compute the values of f(x) at the points B, D, –5, and 5:

In [208]:
x_min = -5
x_max = 5

f.subs({x:B}).evalf()
Out[208]:
$\displaystyle -25.0846626340294$
In [209]:
f.subs({x:D}).evalf()
Out[209]:
$\displaystyle -705.959460380365$
In [211]:
f.subs({x:x_min}).evalf()
Out[211]:
$\displaystyle 375.0$
In [212]:
f.subs({x:x_max}).evalf()
Out[212]:
$\displaystyle -375.0$

Point D turns out be the global minimum¶

GRADIENT ASCENT AND GRADIENT DESCENT ALGORITHM¶

In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 

FINDING THE INTEGRALS OF FUNCTIONS¶

The indefinite integral, or the antiderivative, of a function f(x) is another function F(x), such that $F′(x) = f(x)$. That is, the integral of a function is another function whose derivative is the original function. Mathematically, it’s written as $F(x) = ∫ f(x)dx$.

The definite integral, on the other hand, is the integral:

$\Huge \int_{a}^b f(x)dx = F(b) - F(a)$

where F(b) and F(a) are the values of the anti-derivative of the function at x = b and at x = a, respectively

In [218]:
from sympy import Integral, Symbol

x = Symbol('x')
k = Symbol('k')
I = Integral(k*k, x)
I
Out[218]:
$\displaystyle \int k^{2}\, dx$
In [220]:
I.doit()
Out[220]:
$\displaystyle k^{2} x$
In [221]:
I1 = Integral(k*x, (x, 0, 2))
I1
Out[221]:
$\displaystyle \int\limits_{0}^{2} k x\, dx$
In [222]:
I1.doit()
Out[222]:
$\displaystyle 2 k$

Solve:¶

$\Huge \int_{2}^4 xdx$
In [224]:
from sympy import Integral, Symbol

x = Symbol('x')
Integral(x, (x, 2, 4)).doit()
Out[224]:
$\displaystyle 6$
In [ ]: