11 views

Uploaded by Lulu Tojeen

Pendulum program in c explanation

- 4
- libc
- PDSCt1Solution-Autumn2015
- COMP252 Final 2000F Sol
- C- Program's
- Fast Asymmetric Learning for Cascade Face Detection Training/Testing Utility
- Onehub and EBSCO Case Study
- DOS Command Help
- c Programs
- Plagiarism Detector Log
- C Program to Reverse String Without Using Library Function
- CSE1018Y-1-2012-2
- HSBC Placement Paper | Freshers Choice
- special
- 70-411-R2-Lab05
- CPR - Manual Solutions
- Click
- Opalis Workflow Final
- AS3(2014)
- 3-Data_Storage.pdf

You are on page 1of 8

Numerical solution of differential equations using the Runge-Kutta method.

Writing output data to a file in C programming.

Using GNUPLOT to create graphs from datafiles.

s

tangent

mg

d 2

d 2s

=

L

= g sin

dt 2

dt 2

(1)

where the bob moves on the arc of a circle of radius L, s is parallel to the tangent to this arc

when the angular displacement of the bob from its equilibrium position is , and g sin is

the component of the acceleration due to gravity in the s direction. (N.B. The positive s

direction is chosen to be away from the equilibrium position, in the direction which makes

increase.)

For small angles sin , and equation (1) may be approximated by

d 2

g

2 =

L

dt

(2)

This is a linearised version of equation (1), since the right hand side is linear in whereas

sin in equation (1) is nonlinear. Equation (2) can be solved analytically, giving the usual

periodic solution:

= a sin( t + ),

d

= a cos( t + ),

dt

g

L

(3)

To solve a second order differential equation numerically we introduce a new variable and

transform the second order problem into two first order problems. Introduce the variable

=d/dt which is the angular velocity of the bob, and write

d

= ,

dt

d

= f ( , , t )

dt

(4)

where f(, , t) = 2 sin in the case of the pendulum equation (1), and f(, , t) = 2 in

the case of the linearised equation (2). In the case of a damped pendulum, with damping

force -mk, the function f depends on as well as . If the pendulum is also forced by an

external time-dependent force mA cos(t) the function on the right hand side of (4) becomes

a function of the three variables , and t:

f ( , , t ) = 2 sin k + A cos(t )

(5)

To solve these equations numerically we need to choose initial values for and and then

calculate a series of values for (n, n), n = 1, 2, 3, We step forward in time using Taylor

series expansions for and .

d (t )

d 2 (t ) t 2

t +

+ O(t ) 3

2

dt

2!

dt

t 2

(t + t ) = (t ) + (t )t + f ( (t ), (t ), t )

+ O(t ) 3

2!

n +1 = n + n t + O(t ) 2

(t + t ) = (t ) +

n +1 = n n t + O(t ) 2

This is the simple Euler method for integrating the simple pendulum differential equations.

The notation O(t)2 means that there are error terms of order t squared and higher. The

equation for updating the angular frequency is obtained using a Taylor expansion in the same

way that the equation for updating the angle was obtained.

The trapezoid rule makes improved approximations for updating the angular frequency and

angle.

Trapezoid

Simple

Euler

d (t + t )

dt

d (t )

dt

t+t

d (t ) d (t + t )

+

t + t

d

dt

dt = n +1 n

Area under trapezoid = (t + t t ) dt

dt

2

t

n +1 n +

t d (t ) d (t + t )

+

2 dt

dt

d (t + t ) d (t ) d 2 (t )

=

+

t + O(t ) 2

2

dt

dt

dt

d (t + t )

n + f ( n , n , t )t = n + k1b

dt

t

k1a + k 2a

n +1 n + ( n + ( n + f ( n , n , t ) )t ) = n +

2

2

k1a = n t k2a = ( n + f ( n , n , t )t )t

t d (t ) d (t + t )

+

2 dt

dt

t

k1b + k 2b

n +1 n + ( f ( n , n , t ) + f ( n +1 , n + k1b, t n +1 ) ) = n +

2

2

k 2b = t f ( n +1 , n + k1b, t n +1 )

n +1 n +

The program pendulum.c (provided electronically and on page 4) solves the pair of

equations (4) using the Trapezoid rule:

The program calculates the angle and angular velocity at n+1 instants of time, starting

from t=0 and increasing in steps of equal size h until t=nh. The output is a 3-column

table, with values of t in the first column, in the second and in the third. h is used

instead of t in the actual programme.

The function f(, , t) is calculated in a separate C function, so that it is easy to alter as

necessary.

At each step the integration of the two first order equations is performed using the

trapezoid rule. The variable k1a is h times the value of the derivative of at t, the start of

the step. k2a is h times the first order approximation to the derivative of at t+h. The

trapezoid rule then gives (t+h)= (t)+(k1a+k2a)/2. Similarly k1b and k2b are h times

the values for the derivative of at each end of the step, and the value of at t+h is

calculated using the trapezoid rule.

To make it easy to show the results graphically, the output is written to a datafile as well

as to the screen. The datafile can then be used with GNUPLOT to show graphs of and

against t.

Examine the program pendulum.c to see how data is sent to a file. As well as the statement

commanding the computer to write to the file, the file must be declared, opened before use

and closed after use. (Programming in C section 5). Each of these commands is discussed

below:

Compare the statements

printf("%lf\t%lf\t%lf\n", t, theta, omega);

and

fprintf(Oscp,"%lf\t%lf\t%lf\n", t, theta, omega);

The first will print on the screen

a tab space,

a double precision floating point number taking the current value of theta,

another tab space,

a double precision floating point number taking the value of omega,

a carriage return (invisible of course).

The second command prints exactly the same thing to the file whose address in the computer

memory is Oscp.

In general, the command to print to a file is of the form:

fprintf(file address, "control string", other parameters)

(6)

Remember that when declaring variables their type (int, double, char etc.) must be stated. A

file is a new object of the FILE type. (Note the capitals). The computer must be told where in

its memory the file is saved, so the declaration contains not the file name, but its address. For

example, the declaration for the file with address Oscp is FILE *Oscp . The address is

preceded by an asterisk to indicate that this is a pointer to an area of memory rather than a

name. The declaration for a file is of the general form

FILE *filepointer

(7)

Before data can be written to a file it must be opened. The open file statement has to relate

the file name (as it appears when you look at the contents of the directory in which it resides)

with the address at which it is stored. The statement

Oscp=fopen("pendulum.dat", "w")

opens the file named pendulum.dat. The "w" means that this file is being opened so that it

may be written to. If you wanted to open a file and read from it you would have to use "r",

and if it was a file that already contained data and you wanted to append more data to it you

would use "a". If the file doesn't already exist, the open command creates it.

The file opening statement in pendulum.c is more complicated. Firstly it requests a filename

for the data file. (This makes it easy to ensure that each time you run the program you save

data to a different file). The name is read into the variable filedat as a string of characters.

The declaration of this variable is char filedat[20]; which identifies the input as a character

string of maximum length 20 characters. So in the file opening statement the variable filedat

appears instead of "filename". For use with GNUPLOT the datafile name should have the

extension .dat. (e.g name.dat ).

Secondly the program checks whether it is possible to open the file, and exits with an error

message if it is not. This is good programming style. The file opening statement is of the

following general form:

if ((*filepointer = fopen("filename", "w")) = = NULL)

{ printf("\nCannot open file\n");

exit(1); }

To use the exit function you need to include the header file stdlib.h.

(8)

When you have finished using a file you must close it with a statement of the form

fclose(filepointer);

/* pendulum.c

method */

(9)

# include <stdio.h>

# include <stdlib.h>

# include <math.h>

/* function prototype */

main()

{

int i, n;

double h, k1a, k1b, k2a, k2b, theta, omega, t;

FILE *Oscp;

/* declare file */

char filedat[20];

/* declare string of characters for filename */

h=0.1;

n=100;

theta=0;

omega=1;

t=0;

/* set number of steps */

/* set initial angle */

/* set initial angular velocity */

/* set initial time */

printf("Enter the name of the data file to be written\n");

scanf("%s", filedat);

if ((Oscp = fopen(filedat,"w")) == NULL)

{

fprintf(stderr,"Error opening file %s",filedat);

exit(1);

}

printf("%lf\t%lf\t%lf\n", t, theta, omega);

fprintf(Oscp,"%lf\t%lf\t%lf\n", t, theta, omega);

/* Implement the algorithm: */

for(i=1;i<=n;i++){

k1a=h*omega;

k1b=h*f(theta,omega,t);

k2a=h*(omega+k1b);

k2b=h*f(theta+k1a,omega+k1b,t+h);

theta = theta + (k1a + k2a)/2;

omega = omega + (k1b+k2b)/2;

t=t+h;

printf("%lf\t%lf\t%lf\n", t, theta, omega);

fprintf(Oscp,"%lf\t%lf\t%lf\n", t, theta, omega);

}

fclose(Oscp);

/* close file */

}

double f(double theta, double omega, double t)

{

double deriv;

deriv = -theta;

/* function header */

return deriv;

}

EXERCISES 1

Investigate the motion of a simple pendulum in the particular cases listed below. In each case

write the data to a datafile, and use GNUPLOT to plot graphs of the data.

To plot a datafile, open GNUPLOT. Type plot at the prompt, and pull down the PLOT menu

from the top bar. Click on Data filename and a dialog box will allow you to find any data

files you have saved. Click on the file you want and its name will appear after plot. Now

type using 1:2 and press <RETURN>. GNUPLOT will use the first column of your datafile

for the horizontal axis, and the second column for the vertical axis. To plot the third column

instead of the second, replace 1:2 by 1:3. If you use GNUPLOT with a file pendulum.dat to

plot the angle and angular velocity as functions of time on the same graph, the command line

will be gnuplot> plot 'pendulum.dat' using 1:2, 'pendulum.dat' using 1:3

1. Run pendulum.c as it stands to solve the linearised equation with 2=1 and initial values

=0 and =1. Run the program again with the pendulum initially at rest and the

following set of initial positions: (0)= 0.2 rad, 1.0 rad and 3.124 rad. (The last value is

approximately equal to 179o). In each case plot graphs of and against t. Describe

what the pendulum is doing in each of these cases.

2. Replace the sine function so that the program solves the nonlinear equation (1) for the

same sets of initial values as in question 1. Compare the results with those of question 1.

To see how they differ as the displacement of the pendulum increases, plot the angles

calculated in this question and those found in question 1 as functions of time on the same

graph.

The trapezoid method is accurate to 2nd order in timestep h, which is not sufficient for

integrating the equation for the damped driven pendulum, where the function for the

derivative of is given by equation (5). The second order Runge-Kutta method is derived

below and the 4th order Runge-Kutta algorithm is given for use in your programme. The

second order Runge-Kutta method is based on a Taylor series expansion of the function to be

integrated about the mid-point of the time step.

d (t )

dt

t

d

2

dt

d ( 0)

dt

t

t

) d 2 ( )

d (t )

2 +

2 t t + O( t ) 2

=

2

dt

dt

2

2

dt

t

t

t

d ( )

d 2 ( ) t

d ( )

t

d (t )

t

2

2

2

0 dt dt dt t + dt 2 0 t 2 = dt t + 0

d (

The second term in the series above is equal to zero when we choose the mid-point of the time

step for the Taylor expansion. To use the algorithm we need approximate values for and

at the mid-point of the time step which are generated using the Simple Euler method.

t 2

)

2

t

t

n +1 / 2 n + f ( n , n , t n ) + O( ) 2

2

2

t

n +1 n + n + f ( n , n , t n ) t

2

n +1 n n +1 / 2 t + O(

n +1 n f ( n +1 / 2 , n +1 / 2 , t n +1 / 2 )t + O(

n +1 / 2 n + n

t 2

)

2

t

2

t

2

n + f ( n +1 / 2 , n +1 / 2 , t n +1 / 2 )t

n +1 / 2 n + f ( n , n , t n )

n +1

The algorithm for second order Runge-Kutta integration has been derived; formulae for the

4th order Runge-Kutta method are given below.

k1a = h

k2a = h (+k1b/2)

k3a = h (+k2b/2)

k4a = h (+k3b)

k1b = h f(, , t)

k2b = h f(+k1a/2, +k1b/2, t+h/2)

k3b = h f(+k2a/2, +k2b/2, t+h/2)

k4b = h f(+k3a, +k3b, t+h)

(t+h) = (t) + (k1b+ 2 k2b + 2 k3b + k4b)/6

EXERCISES 2

1.

Edit pendulum.c so that it uses the 4th order Runge-Kutta algorithm in the for loop.

2.

Check your program by running it for the case of the nonlinear equation (1), with

several different initial values of and , and comparing the results with those

obtained in question 2 of exercise 1.

3.

Examine the behaviour of a damped pendulum, equation (5), using 2=1, k = 0.5, A=0

and a range of initial positions and velocities. Plot graphs of against t to compare

the nonlinear case with the linearised version. Your graphs should show that the

linear approximation becomes very good after a sufficiently long time. Explain why.

4.

Change the function in your program to solve the equation for the damped driven

pendulum, using 2=1, k = 0.5, = 0.6667, and a range of drive amplitudes:

A = 0.90, 1.07, 1.35, 1.47 and 1.5. The best way to understand the behaviour of the

pendulum is to plot graphs of against , and restrict to the range [-, ]:

To restrict the range of , add the following if statement in the for loop where

theta is calculated:

if (fabs(theta)>PI)

{

theta = theta - 2*PI*fabs(theta)/theta;

}

To use PI instead of having to type in the numerical value, define it at the very

top of your program with the statement # define PI 3.14159265 (N.B. no

semicolon at the end).

It is convenient to divide the 'drive period' 2/ into an integer number N of

steps (e.g. N=1000), and calculate values of and at each of these times over a

small number of drive cycles (e.g. 5).

Approximately the first 500 iteration points represent an initial transient

trajectory before the motion settles down. Do not plot the first 500 points

(include a statement in your program to prevent it writing the initial 500 points to

the datafile).

Plot against for initial positions and velocities in the ranges -3.0<(0)<-1.0,

-0.5<(0)<0.5. For A = 0.90 you should be able to see that the motion is periodic,

while for A = 1.07 it is a combination of oscillations at two different periods - period

doubling has occurred. For A = 1.5 the motion is chaotic.

- 4Uploaded byAqsa Akhtar
- libcUploaded bySoumodip Chakraborty
- PDSCt1Solution-Autumn2015Uploaded byaarush khatri
- COMP252 Final 2000F SolUploaded bymrdinggind
- C- Program'sUploaded bySureshbabu Kunchala
- Fast Asymmetric Learning for Cascade Face Detection Training/Testing UtilityUploaded bypi194043
- Onehub and EBSCO Case StudyUploaded byOnehub
- DOS Command HelpUploaded byCityMaster
- c ProgramsUploaded byremu123
- Plagiarism Detector LogUploaded byLiliana Băjănaru
- C Program to Reverse String Without Using Library FunctionUploaded bycoldredcoldred
- CSE1018Y-1-2012-2Uploaded byMasterArvin
- HSBC Placement Paper | Freshers ChoiceUploaded byfresherschoice
- specialUploaded byapi-289794975
- 70-411-R2-Lab05Uploaded byJacob Vowles
- CPR - Manual SolutionsUploaded byapi-3728136
- ClickUploaded byIndira Hatibovic
- Opalis Workflow FinalUploaded byanupgarg123
- AS3(2014)Uploaded bydebeal
- 3-Data_Storage.pdfUploaded byNischitha Nish K V
- 5_Programming of MicroprocessorUploaded bykimabz03
- ‘C’ Programming LanguageUploaded byAnup Bharadwaj
- Manual Configuration ManagementUploaded bycora354
- 998TUploaded byOtto Chung
- Advanced CAN DocuUploaded byAmine Toukabri
- Overview dari Bahasa CUploaded byAsaCircle
- Doubt[1]Uploaded byMani Kandan
- 78 - 7 - Sliding Contact BearingUploaded byrip111176
- crack wepUploaded byj0aki
- practr2Uploaded byMario Pérez

- Programming Languages 1Uploaded byLulu Tojeen
- mod5Uploaded byLulu Tojeen
- mod4Uploaded byLulu Tojeen
- Handling Global Resources(6)Uploaded byLulu Tojeen
- Java Remote Method InvocationUploaded byLulu Tojeen
- Design of Associations(7)Uploaded byLulu Tojeen
- OOMDmodule_3__1Uploaded byNeethu Rachal George
- mod1Uploaded byLulu Tojeen
- mod1Uploaded byLulu Tojeen
- Names,VariablesUploaded byLulu Tojeen
- Implementation of Control(5)Uploaded byLulu Tojeen
- Designing Algorithms (3)Uploaded byLulu Tojeen
- _Here to Help You__ Computer Networks_ InterviewUploaded byLulu Tojeen
- OOMD module_2__3Uploaded bySujay Ps
- Sensor NetworksUploaded byLulu Tojeen
- Java Programming Lab Part 1Uploaded byLulu Tojeen
- ChemistryUploaded byLulu Tojeen
- Module 1Uploaded byLulu Tojeen
- eeeUploaded byLulu Tojeen
- ABC 6567 DefUploaded byNeelakandan Pradeesh Kumar
- Application of DSP in Video CompressionUploaded byLulu Tojeen
- Computer Graphics Question paperUploaded byLulu Tojeen
- DBMS notesUploaded byLulu Tojeen
- DBMS notesUploaded byLulu Tojeen
- OOMD question paper MG universityUploaded byLulu Tojeen
- Compiler Construction PaperUploaded byLulu Tojeen
- A Single Camera Based Floating Virtual KeyboardUploaded byLulu Tojeen
- MC1704_Computer_Graphics_and_Multimedia_SystemUploaded byAbhinav Rana

- Norwegian Deepwater Program- Damping of Vortex-Induced VibrationsUploaded byhyfundnd
- 11_030_gatt.pdfUploaded byjoebriffa
- Underground Coal Mine Lighting Handbook-1Uploaded byTommyc1024
- Thermal Stresses n Composite Bar Baya Slide Power PointUploaded bysofwanazmin
- catalogo_9P2-004E.pdfUploaded byNguyenHuan
- $$ TASSIN Planar Designs for ElectromagneticallyUploaded byDaniel Lucena
- Application of a Corona Onset Criterion to Calculation of Corona Onset Voltage of Stranded ConductorsUploaded byJose Manuel Camacho
- Part1 Fluids Rock PropertiesUploaded byKaro Huenufil Molina
- 5-3_Polynomial_Functions[1].pdfUploaded byEnas Basheer
- J. Org. Chem. 1986,51, 1882-1884.pdfUploaded byMari Corsaletti
- COMMON ION EFFECT AND BUFFERS ATQ.docxUploaded byPancho Villamoran
- AP Chemistry Summer Assignment 2015.docxUploaded byDang Pham
- Unsteady Aerodynamics posterUploaded byKiran Ramesh
- ASTM E168.pdfUploaded byPablo Emilio Martinez Garcia
- SolidWorks 2012 Part I - Basic ToolsUploaded byabozarsam
- Oceanography Q & a for Topic 1Uploaded byr_kolomiets
- Cell PackUploaded byKuchai
- Main Thesis SkaugeUploaded byPakeeza Akram
- Kelompok 6 - Combined Controlled System ElementsUploaded bydwi safitri
- Chemical Thermodynamics IIT Part 1Uploaded byAdiChemAdi
- Camphor Water PpnUploaded bysamiveni
- UV y IR fotografíaUploaded byMarcos Gianetto
- FKM Guideline: Strengths, Limitations and Experimental ValidationUploaded byAnonymous wdnkofW
- Cosmic Inspiration Lovecraft's Astronomical Influences by Brown UniversityUploaded byEnano3255
- m u t u a l u f oUploaded bySAB78
- Flow Meter Lab ReportUploaded byMadiha Zaimuri
- An Overview of Effect of Splitter Blades on Centrifugal Pump PerformanceUploaded bybhaveshlib
- Mahr 3759665 FL Dimensional Metrology Catalog USA 2011 EnUploaded byAdam Awg
- Mig Wire Feeding IssuesUploaded by0502ravi
- Monouso Ge Healthcare, Catalogo prodotti GE HealthcareUploaded byAlessandro Armaroli