You are on page 1of 9

ME2 Computing- Tutorial 3: Numerical

Differentiation/Integration

Summary
Use Matlab for numerical differentiation.
Use Matlab for numerical integration
Use Matlab to solve a differential equation

Introduction

In engineering equations that govern the behaviour of a system are often in
form of differential equations. As the name suggests they contain derivatives
and can be difficult to solve analytically. There are very simple and effective
techniques to approximately calculate a derivative numerically using a
computer. These techniques can also be applied to solve differential
equations where finding an analytical solution might prove to be difficult.
Similarly numerical techniques can be used to integrate functions that can not
easily be handled analytically. Thus the solution of equations can prove to be
a very useful tool to approximate/describe the behaviour of an engineering
system. In this tutorial some basic methods of numerical calculus will be
explored. Then the numerical solution of a differential equation will be worked
through and a simple engineering problem will be solved.
ME2 Computing 2014 1 Tutorial 3 (week 4)

Task A: Numerical differentiation




Consider an arbitrary function y =f(x) as shown in the above figure. The
derivative of the function dy/dx is to be determined. The derivative is defined
as the slope of the function at x, i.e.
x
y
dx
dy
x

=
0
lim [ 1]

Assuming that x is small several numerical approximations to the derivative
are possible.

The backward difference estimate at xi (as shown by the line A in the above
figure) is defined by


1
1

=
i i
i i
backward
x x
y y
dx
dy
[ 2]

(Pay attention to the first index i=1, for this value the backward difference is
not defined as the index i-1=1-1=0 does not exist. Matlab array indices always
start at 1! If it is not defined you will have to leave it out.)

The forward difference estimate at xi (as shown by line B) is defined by

i i
i i
forward
x x
y y
dx
dy

=
+
+
1
1
[ 3]

(Again pay attention to the indices, the last index i=n+1 is not defined as y
only has n elements. N+1 does not exist and the forward difference is not
defined.)


ME2 Computing 2014 2 Tutorial 3 (week 4)


And there is also a central difference estimate at xi which uses the points to
either side of xi and yi, i.e.

|
|
.
|

\
|

=
+
+

i i
i i
i i
i i
central
x x
y y
x x
y y
dx
dy
1
1
1
1
2
1
. [ 4]

For the following work save all your commands in an m-file so that you can
execute them several times with slightly different settings.

1. Create a vector x with 20 linearly spaced numbers between 0 and
4 (use the l i nspace command).

2. From x create a new vector y = sin x.

3. Write a little script that calculates the backward difference
estimate of the derivative of y with respect to x.

4. Plot dy/dx and also the true derivative y = cos x.
(Hint: use the di f f function to calculate the difference between two
consecutive vector elements. For more information on the di f f
function look it up in the Matlab help.)

5. Now also compute the forward and central difference estimates of
the derivative and plot all of the results on the same graph (use
hol d to display all graphs in the same plot, give the graphs different
colours).

6. Find the maximum deviation from the true value (dy/dx = cos x)
for each scheme.

7. Now reduce x using 100 elements between 0 and 4 (use
l i nspace). What is the maximum deviation for each scheme now?

As expected the smaller the step x becomes the more accurate the
numerical evaluation of the derivative becomes.













ME2 Computing 2014 3 Tutorial 3 (week 4)

An important aspect that governs the accuracy to which the derivative can be
determined is the spread or error in the function/data that is to be numerically
differentiated.

8. In order to explore this create a new vector containing elements y
= (sin x) 0.01 random error. (Use the r and function to create the
random error).

9. Again use your derivative scripts to evaluate the numerical
derivative of the new y function that contains errors.

How large are the deviations of the different schemes now?


Useful Matlab functions for this section:

l i nspace
- creates a vector with uniformly spaced elements
di f f
- calculates the difference between adjacent elements in a
vector
end
- defines the end of a vector, useful in matrix manipulation
l engt h
- returns the length of a vector
r and
- creates a random number

If you are unclear of how to use any of these functions either type help
function (e.g. help mkdir) followed by enter into the Matlab command
window or open the Matlab help browser and use the search tool to search for
the documentation relevant to the desired function.

Answer Quiz Question Tutorial 3 Task A

ME2 Computing 2014 4 Tutorial 3 (week 4)


Task B: Numerical Integration

Integration calculates the area under a curve. Numerical integration is very
useful when the analytical form of an integral is unknown or when it would be
very difficult to find the solution otherwise. Consider a function y=f(x).



The easiest way to evaluate the integral of a function is by approximating
each datapoint(x,y) by a bar of height y and width x. Where x=x2-x1. This
method is very crude but gives an approximate answer. A better method is to
use trapezoidal elements and use the trapezium rule for integration. Matlab
has its own function to carry out integration using the trapezium rule, it is
called by t r apz( x, y) .
Where x and y are vectors of the function y=f(x). t r apz( x, y) performs
numerical integration given the 2 vectors x and y. In order for this to work x
and y must be of the same length.

1. Integrate y=-(x-2)
2
+4 in the interval from 0 to 4 using the trapezium
rule in matlab.

2. Compare your result to the analytical solution
4
0
3
2
3
2
(

=
x
x I .

3. What is the maximum step size x to avoid making the error larger
than 1%? (answer=0.4)

Numerical integration using the trapezium method is most prone to error in
regions where a function is changing rapidly (for example between x1 and x2
in the figure above). Using adaptive methods, i.e. by changing the step size
locally where these fast changes occur, the accuracy of the result can be
improved. t r apz( x, y) is not adaptive. However the Matlab function quad is
adaptive, but it can only be used on functions and not on vectors of data as
for t r apz.

ME2 Computing 2014 5 Tutorial 3 (week 4)

quad( a, b) uses an adaptive form of Simpsons rule (See your 1M maths
notes for more information) to evaluate the integral of a function between two
specified limits.

4. Use quad to integrate the function sqr t ( x) from 0 to 1.

5. Now create your own function myint for y = -(x-2)
2
+ 4 and use
quad to evaluate the integral from x = 0 to x = 4.

6. Compare the result with the one you found earlier.

The error tolerance to which quad evaluates the integral can be adjusted by
an extra argument t ol when calling the function. You can find out about this
in the Matlab help.


Answer Quiz Question Tutorial 3 Task B


Useful Matlab functions for this section:

l i nspace
- creates a vector with uniformly spaced elements
pl ot
- plots two vectors
t r apz
- numerical integral of a curve described by two data vectors
quad
- numerically integrates a function

If you are unclear of how to use any of these functions either type help
function (e.g. help mkdir) followed by enter into the Matlab command
window or open the Matlab help browser and use the search tool to search for
the documentation relevant to the desired function.
ME2 Computing 2014 6 Tutorial 3 (week 4)


Task C: Numerical solution of a differential equation (Euler
method)


Consider the simple Ordinary Differential Equation (ODE)
) ( ) ( t y t F
dt
dy
= . [ 5]
Where F(t) is a known function and you want to determine y(t). While
analytical solutions to this problem exist a numerical solution can also be
found. The advantage of the numerical solution is that it is based on a simple
difference equation and can be solved quickly even in cases when an
analytical solution is not known. However there are usually drawbacks: it is
only an approximation and if some parameters such as the step size are
poorly selected, the numerical routine can lead to large errors.

One of the simplest and crudest methods to solve ODEs is the Euler method,
which will be explored below:

The derivative in equation [1] is expressed as a finite difference

t
t y t t y
t
t y t t y
dt
dy
t

+
=

) ( ) ( ) ( ) (
lim
0
[ 6]

Using this to re-write equation [1] results in

) ( ) (
) ( ) (
t y t F
t
t y t t y
=

+

or

( ) t t F t y t t y t F t y t t y + = + = + ) ( 1 ) ( ) ( ) ( ) ( ) ( . [ 7]

This shows that we can evaluate any future value of y if we know an initial
value of y (i.e. y(t)), the function F(t) and use a small time step t (larger t
will cause larger errors but decrease the computation time).

It is convenient to write the equation in terms of time steps rather than simply
time, i.e.:

t t y t F t y t y
k k k k
+ =
+
) ( ) ( ) ( ) (
1
. [ 8]

1. Now use equation [8] to evaluate y(t) of equation [5] for F(t) = - 2,
y(0) = 2, t = 0.02 over the range t = 0 t = 3.
(Hint: You will have to write a script that calculates a new y for each
time step. The initial value y(0) gives you the starting point.)

2. Compare the answer to the analytical solution y=2e
-2t
.
ME2 Computing 2014 7 Tutorial 3 (week 4)


3. In subtask 1 increase the time step size t to 0.2 (and then to 0.4)
and recalculate y(t). Plot the result and the analytical solution
(subtask 2) on the same graph and compare the two curves. Plot
both curves in a different colour so that you can differentiate them.

4. Calculate the maximum deviation between the analytical solution
and the solution obtained using the Euler method for t = 0.02, 0.2
and 0.4.


Answer Quiz Question Tutorial 3 Task C


Useful Matlab functions for this section:

f or end
- Loop that repeats the statements within the described block
for a predefined number of times
pl ot
- plots two vectors

If you are unclear of how to use any of these functions either type help
function (e.g. hel p mkdi r ) followed by enter into the Matlab command
window or open the Matlab help browser and use the search tool to search for
the documentation relevant to the desired function.
ME2 Computing 2014 8 Tutorial 3 (week 4)

Task D: RC circuit example


An RC circuit (resistor - capacitor), as shown above, has the following
characteristic equation:
0 = + y
dt
dy
RC . [ 9]
The value for R =100k and C =1F so that RC =0.1, no voltage is applied
and the initial voltage across the capacitor is y(0) =2V so that the equation
reduces to:
0 1 . 0 = + y
dt
dy
. [ 10]
1. Write a little script that evaluates y as a function of t (from t=0 to
t=3secs)

2. Find the the solution for y for t=0.01 .
The power delivered by the circuit is the product of VI (voltage V and current I)
and the energy stored in the capacitor is the integral of VI with respect to time.
3. Find the energy stored in the capacitor at t=0 by numerically
integrating the power (VI). (Hint: V=RI, knowing V you can calculate I)

The solution will always slightly change as t is further reduced
however the changes become less and less important. Usually a
tolerance is set and if the solution changes by less than a predefined
error tolerance say 0.01 in this case the result is close enough to the
real solution.

4. Reduce the steps size from t=0.01 (by dividing by 10) until the
solution of the energy stored in the capacitor changes by less than 1%.
The solution can then be believed to have converged to the real value.
Answer Quiz Question Tutorial 3 Task D
Useful Matlab functions for this section:

pl ot
- plots data
t r apz
- numerical integral of a curve described by two data vectors

If you are unclear of how to use any of these functions either type help
function (e.g. help mkdir) followed by enter into the Matlab command
window or open the Matlab help browser and use the search tool to search for
the documentation relevant to the desired function.
ME2 Computing 2014 9 Tutorial 3 (week 4)

You might also like