Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

MP Lab File 02

The document discusses approximating elementary functions like exponential, sine and cosine using Taylor series. It explains implementing Taylor series approximations of these functions in Python by defining functions for each and plotting the approximations against the actual functions for different orders of the Taylor series. It also discusses numerically calculating position and velocity from acceleration data using trapezoidal and Simpson's rule of numerical integration in Python.

Uploaded by

mr.hike.09
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

MP Lab File 02

The document discusses approximating elementary functions like exponential, sine and cosine using Taylor series. It explains implementing Taylor series approximations of these functions in Python by defining functions for each and plotting the approximations against the actual functions for different orders of the Taylor series. It also discusses numerically calculating position and velocity from acceleration data using trapezoidal and Simpson's rule of numerical integration in Python.

Uploaded by

mr.hike.09
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

PROGRAMME—12

AIM– To approximate the elementary functions( exp(x),sin(x),cos(x)) by a finite number of


terms of Taylor's series and discuss the truncation error.

THEORY—

The Taylor series or Taylor expansion of a function is an infinite sum of terms that are
expressed in terms of the function's derivatives at a single point. A one-dimensional Taylor
series is an expansion of a real function f(x) about a point x=a is given by-

where f(n)(a) denotes the nth derivative of f evaluated at the point a.

The partial sum formed by the first n + 1 terms of a Taylor series is a polynomial of degree n
that is called the nth Taylor polynomial of the function. Taylor polynomials are
approximations of a function, which become generally better as n increases.

If the Taylor series of a function is convergent , its sum is the limit of the infinite sequence
of the Taylor polynomials.

Truncation error– The difference between the true or analytical derivative of the value of a
function and the value obtained from numerical approximation is the truncation error.

Taylor expansion of exp(x)


Taking the expansion about x=0:

Taylor expansion of sin(x)


Taylor expansion of cos(x)

INPUT:-

i) exp(x)
ALGORITHM–

1) Import numpy and matplotlib.


2) Define a function taylor_exp
3) Use loop to implement the taylor series for exponential function
4) Use linspace to create a range of x values
5) Create a list for various orders of taylor series to be obtained
6) Use looping and list comprehension to create a separate list of corresponding y
values
7) Plot the results using the grid function
8) Adjust the figure size accordingly
Input–
import numpy as np

import matplotlib.pyplot as plt

def taylor_exp(x, n):

result 0.0

for i in range(n):

coeff=1/np.math.factorial(1)

term=coeff* x**i

result += term

return result

#Define the range of x values x= np.linspace(-5, 5, 1000)

Compute the exponential values using the Taylor series jpproximation with different orders

n_values = [1, 3, 5, 7, 9] #Orders of the Taylor series

y_values = [ ]

for n in n_values:
y=[taylor_exp(val, n) for val in x]
y_values.append(y)

#Plot the results

plt.figure(figsize(10, 6))

plt.plot(x, np.exp(x), label='exp(x)') #True exponential function

for i, y in enumerate(y_values):
plt.plot(x, y, label f'Taylor Series (Order (n_values[i]}}')

plt.xlabel('x')

plt.ylabel('y')

plt.title('Taylor Series Approximation of exp(x)')

plt.legend() plt.grid(True)

plt.show()

OUTPUT–
ii) sin(x)
ALGORITHM–

 Import numpy and matplotlib. 2)Define a function taylor_sin


 Use loop to implement the taylor series for sin 4)Use linspace to create a range of x
values
 Create a list for various orders of taylor series to be obtained
 Use looping and list comprehension to create a separate list of corresponding y
values
 Plot the results using the grid function
 Adjust the figure size accordingly

Input–

import numpy as np

import matplotlib.pyplot as plt

def taylor_sine(x, n):

result = 0.0

for i in range(n):

coeff = (-1)**1/np.math.factorial(2*1 + 1)
term = coeff * x**(2*1+1)
result += term

return result

#Define the range of x values


x = np.linspace(-2*np.pi, 2 np.pi, 1000)

#Compute the sine values using the Taylor series approximation with different order

n_values = [1, 3, 5, 7, 9] #Orders of the Taylor series

y_values = []

for n in n_values:

y=[taylor_sine(val, n) for val in x] y_values.append(y)

#Plot the results

plt.figure(figsize=(10, 6))

plt.plot(x, np.sin(x), label='sin(x)') # True sine function

for i, y in enumerate(y_values):

plt.plot(x, y, label=f'Taylor Series (Order {n_values[i]}}')

plt.xlabel('x')
plt.ylabel('y')
plt.title('Taylor Series Approximation of sin(x)')
plt.legend()
plt.grid(True)
plt.show()

OUTPUT–

iii) cosx
ALGORITHM–
 Import numpy and matplotlib. 2)Define a function taylor_sin
 Use loop to implement the taylor series for sin 4)Use linspace to create a range
of x values
 Create a list for various orders of taylor series to be obtained
 Use looping and list comprehension to create a separate list of corresponding y
values 7)Plot the results using the grid function
 Adjust the figure size accordingly

INPUT–

import numpy as np

import matplotlib.pyplot as plt

def taylor_cos(x, n):


result = 0.0

for i in range(n):

coeff = (-1)**i / np.math.factorial(2*1) term =coeff * x**(2*i)


result += term

return result

#Define the range of x values


x = np.linspace(-2*np.pi, 2*np.pi, 1000)

#Compute the cosine values using the Taylor series approximation with different orders

n_values = [1, 3, 5, 7, 9] # Orders of the Taylor series

y_values = []

for n in n_values:

y = [taylor_cos(val, n) for val in x] y_values.append(y)

#Plot the results

plt.figure(figsize=(10,6))
plt.plot(x, np.cos(x), label='cos(x)') # True cosine function

for i, y in enumerate(y_values):

plt.plot(x, y, label=f'Taylor Series (Order {n_values[1]}}')

plt.xlabel('x ')
plt.ylabel('y')
plt.title('Taylor Series Approximation of cos(x)')
plt.legend()
plt.grid(True)
plt.show()

OUTPUT–
UNIT 5–

NUMERICAL INTEGRATION PROGRAM


PROGRAMME—13
AIM– Given acceleration at equidistant time values,calculate position and velocity and
plot them.

THEORY—-

Trapezoidal method—

Trapezoidal Rule is a rule of numerical integration that evaluates the area under the curves
by dividing the total area into smaller trapezoids rather than using rectangles. This
integration works by approximating the region under the graph of a function as a trapezoid,
and it calculates the area. This rule takes the average of the left and the right sum.

The integration of a function y for an interval from x0 to xn can be given by the trapezoidal
rule as

The geometrical significance of this rule is that the curve y = f (x) is replaced by n straight
lines joining the points (x0, y0) and (x1, y1); (x1, y1) and (x2, y2), >, (xn−1, yn−1) and (xn,
yn). The area bounded by the curve y = f (x), the ordinates x = x0 and x = xn, and the x-axis is
then approximately equivalent to the sum of the areas of the n trapeziums obtained.

Simpson’s ⅓rd rule —-

Simpson’s 1/3rd rule is an extension of the trapezoidal rule in which the integrand is
approximated by a second-order polynomial.Simpson’s rule methods are more accurate
than the other numerical approximations.

It should be noted that this rule requires the division of the whole range into an even
number of subintervals of width h.

ALGORITHM–

1) import numpy and matplotlib module


2) create and empty list and run a loop to add elements with step size 0.1

3) convert the list to array

4) Create an array with constant acceleration values using numpy ones function

5) Define a function for velocity and implement the trapezoidal formula for numerical
integration.

6) Run a loop to evaluate the value of velocity over a range of values.

7) Define a function for position and implement the trapezoidal formula for numerical
integration.

8) Run a loop to evaluate the value of position over a range of values.

9)Plot both velocity vs time and position vs time graph

INPUT CODE–

import numpy as np

import matplotlib.pyplot as plt

list=[]

x=0

while x<10 ог х==10:

list.append(x)

x=x+0.1

t=np.array(list)

n=len(t)

a=9.8*np.ones(n)

def v(i):

if i<0:

return 0

else:

return ((0.05%(a[i-1]+a[i]))+v(i-1))
list2 = []

for i in range(0,101):

list2.append(v(i))

v=np.array(list2)

def p(1):

if i<0:

return 0

else:

return ((0.05*(v[i-1]+v[i]))+p(1-1))

list3=[]

for i in range(0,101):

list3.append(p(i))

p=np.array(list3)

print(v)

print(p)

plt.plot(t,v,label="Velocity", c="r")

plt.plot(t,p, label="posiiton",c="b")

plt.title(“Velocity bs time & Position vs time”)

plt.show()
PROGRAMME—14
AIM– Verify the properties of Delta Dirac Function using the representation as a sequence of
functions.

Theory—
Delta Dirac Function

The Dirac delta function is a generalized function that is best used to model behaviors similar
to probability distributions and impulse graphs.

It is represented as–

Some properties of dirac delta function—

1) Property 1— the dirac delta function is equal to 0 when x is not equal to xo.

2) Property 2— By integrating the Dirac delta function, we can show that the function is
equal to 1 within the allowed interval.

3) Property 3— We can extend the second property to account for instances when we
multiply delta (x) with a function, f(x)--

ALGORITHM–

1) Import numpy, integrate from scipy,matplotlib,math module.


2) Create a array of values using linspace
3) Create an empty list which will be used to store the values of dirac function
4) Use spipy integrate function for integration.
5) Plot the various values of delta dirac function.
INPUT CODE—
import numpy as np
import scipy.integrate as spi
import matplotlib.pyplot as plt
import math

lis=np.linspace(0.1,0,100)

res=[]

for s in lis:

integrand = lambda x: ((1.0/(s*math.sqrt(2*math.pi)))*math.e**(-((x-2)**2)/(2

a=1.9

b=2.1

result, error=spi.quad(integrand,a,b)

res.append(result)

plt.plot(lis, res)

plt.title("Dirac delta function")

plt.show()

OUTPUT CODE–

You might also like