runge-kutta differential equations

Upload: dan-cook

Post on 09-Apr-2018

242 views

Category:

Documents


1 download

TRANSCRIPT

  • 8/8/2019 Runge-Kutta Differential Equations

    1/25

    RungeKuttaNumericalMethodsusedinEvaluationof

    DifferentialEquations

    DanielCook

    Abstract

    Periodicmotionisoneofthemostcommonengineeringissuesfaced. Thegoaloftheseproblemsisto

    modelthisperiodicmotionasafunctionoftime,resultinginadifferentialequation. Tosolvethese

    differentialequationsseveralmethodsarecommonlyemployed. Themethodsthatwillbedescribedin

    thispaperareallvariationsofRungeKuttamethods,specificallytheEulermethod,Heunsmethod,

    Midpointmethod,andtheclassicfourthorderRungeKuttamethod.

    Introduction

    Theneedtosolveperiodicmotionisseeninmanyaspectsofengineering.Wavesandpendulumsare

    twoexamplesofperiodicmotionfoundineverydayproblems.Pendulumsspecificallyhavefoundmany

    importantuses. Consideredtobeoneofthemostexactformsoftimekeepinguntiltheinventionofthe

    quartzclock,pendulumsplayedavitalroleinearlytimemanagement.

    Periodicmotionisalsoseeninmolecularvibration.Molecularvibrationiswhenamoleculeasawhole

    hasconstanttranslationalandrotationalmotion.Theinformationgainedfromknowingtheismolecular

    vibrationisveryimportantingaininginsightintotheSchrodingerwaveequation,whichlaysthe

    foundationformodernquantummechanics[1].

    Tomodeltheseproblems,positionandvelocityoftheobjectmustbeknownasafunctionoftime. The

    functionsthatmodelthismotionarecommonlyseenasdifferentialequations,meaningthatthevalues

    ofthefunctionarebasedoffofthefunctionitselfanditsderivatives. Differentialequationscanbecome

    verycomplex,andnumericalmethodsarecommonlyemployedtosolvetheseequations. Fourmethods

    willbeusedinthispapertosolvethemotionofapendulum.ThesemethodsaretheEulermethod,

    Heunsmethod,theMidpointmethod,andfinallytheFourthorderRungeKuttamethod.

    PhysicalAnalysis

    Asstatedabove,thispaperwillfocusontheharmonicmotionofapendulumsystem.Thissystemis

    showninfigure1.

  • 8/8/2019 Runge-Kutta Differential Equations

    2/25

    Inthissys

    Themass

    Theforce

    forceint

    termof

    Thissyste

    However,

    anglessin

    Fromthis

    Thisisag

    solution

    ofthesys

    systemof

    temthereis

    isinitiallysu

    sactingont

    estring. Kn

    andL.

    mcanbemo

    thissecond

    ,wecan

    wecansolv

    eneralrepre

    ssumesthat

    temanumer

    twofirstord

    Figu

    anobjectof

    pendedata

    emass,allo

    wingthis,th

    deledusing

    orderdiffere

    transformth

    fortheangu

    entationoft

    sinwhic

    icalsolution

    erequations

    re1:PhysicalS

    assmatta

    glefrom

    ingittoosc

    epositionof

    ewtonslaw

    tialequatio

    eequationin

    lardisplace

    hesystem,b

    isonlyvalid

    isrequired.B

    canbeobtai

    tupofPendul

    chedtoafix

    whichitisre

    illate,aregra

    themassal

    ofmotion,

    sin 0hasnoanal

    toamorem

    0 (2)

    entattime

    cos

    utitsaccura

    atsmallang

    ysubstitutin

    ned[2]:

    umSystem[2]

    dpointPb

    leasedando

    vityactingo

    ngitspatho

    hichtakest

    (1)

    yticalsolutio

    anageableli

    t[2]:

    (3)

    ycanbecall

    ulardisplace

    gv=d/dtint

    yastringor

    scillatesina

    themassa

    fmotioncan

    eform[2]:

    n. Butknowi

    eardifferent

    edintoques

    ents. Too

    oequation(

    odoflength

    harmonicm

    dthetensile

    bedescribe

    ngthatats

    ialequation

    ionbecause

    tainabetter

    )acoupled

    L.

    tion.

    in

    all

    [2]:

    this

    view

  • 8/8/2019 Runge-Kutta Differential Equations

    3/25

    (4)

    And

    sin (5)

    Thenumericalmethodslistedabovecanthenbeusedtosolvethiscoupledsystem.

    Additionally,bysubstitutingequation(3)intoequation(4)weobtainafirstorderdifferentialequation

    thatcanbeusedtopredictthevelocity[2]:

    sin cos (6)

    Whichcanbesolvedforbyintegration.

    NumericalAnalysis

    AllfourofthenumericalmethodsmentionedarevariationsoftheRungeKuttamethods. TheRunge

    Kuttamethodsallrelyonthesamegeneralideaoffindinganewvaluebasedonapreviousvaluebeing

    modifiedbytheslopeorderivative,andanincreaseintheindependentvariable(astep).

    Inequationformthiscanberepresentedas:

    Orinamoremathematicalview[3]:

    (7)

    Where istheslopeorderivative,andhisthestepsize.

    EulersMethod(FirstOrderMethod)

    Eulersmethodusesthefirstderivativeofthefunctionattheoriginalxvaluetoextrapolateanewy

    value. Thismeansthatforthismethod =f(xi,yi)=y,whichisthederivativeattheinitialxvalue. The

    generalformulaforthismethodis[3]:

    ,

  • 8/8/2019 Runge-Kutta Differential Equations

    4/25

    Graphical

    Theitera

    findanot

    HeunsM

    Heunsm

    pointswh

    valueare

    interval.

    Thismeth

    averaged

    corrector

    Predictor:

    Corrector

    Thiscan

    lythiscanbe

    iveprocess

    ernewpoin

    ethod(Seco

    ethodiskno

    endetermin

    averagedto

    odbeginsby

    withtheslo

    formulasare

    :

    edepicted

    g

    seenas:

    fextrapolati

    tcontinuesf

    dOrderMe

    nasasecon

    inganewval

    obtainaslop

    findingapr

    eattheiniti

    asfollows[3

    raphicallyas:

    Figure2:

    ganewpoi

    rthedurati

    hod)

    dordermet

    ue. Thederi

    ethatisabe

    dictor,whic

    lvaluetoob

    ]:

    Euler'sMetho

    tbasedofft

    nofthefun

    hodbecause

    ativeatthe

    tterrepresen

    istheslope

    tainthecorr

    , ,

    [4]

    hederivativ

    tioninterval

    ittakesthef

    initialvalue

    tationofthe

    attheendp

    ectorequati

    ,

    ,thenusing

    .

    unctionsderi

    ndthederiv

    actualslope

    oint. Thispr

    n. Thepred

    thatnewpoi

    vativeattw

    tiveatthee

    acrossthe

    dictoristhe

    ictorand

    ntto

    nd

  • 8/8/2019 Runge-Kutta Differential Equations

    5/25

    Midpoint

    Themidp

    tofindne

    midpoint

    methodt

    [3]:

    Graphical

    Method(Se

    ointmethod

    wvalues. Th

    methodtake

    akestheave

    lytheMidpo

    ondOrder

    isverysimila

    emaindiffer

    sthederivati

    ageofthed

    intmethodc

    Figure3:

    ethod)

    rtoHeuns

    encebetwee

    veatthemi

    rivativesatt

    nbedepict

    Heun'sMetho

    ethodintha

    nthemidpoi

    pointbetwe

    heinitialand

    .,

    das:

    [5]

    titusesderi

    ntmethoda

    entheinitial

    endvalues.

    .

    ativesattw

    ndHeunsm

    andendval

    Theformula

    separatep

    thodisthe

    e,whileHeu

    forthismeth

    ints

    ns

    odis

  • 8/8/2019 Runge-Kutta Differential Equations

    6/25

    FourthO

    Asthena

    betterap

    gainamu

    Where

    Thismeth

    Graphical

    derRunge

    meimplies,t

    proximateth

    chmoreacc

    odtakesthe

    lythiscanbe

    uttaMetho

    heFourthOr

    eslopeinth

    ratereprese

    derivativesa

    seenas:

    Figure4:

    derRungeK

    giveninterv

    ntationofth

    1

    6

    ttheinitialv

    idpointMeth

    ttamethod

    al. Itthenw

    eactualslop

    2

    , .5, . .5, . , alue,twoat

    d[6]

    takesderivat

    eightseacho

    e.Theformu

    55themidpoint

    ivesatfourd

    fthesederiv

    laforthisis[

    ,andoneat

    istinctpoint

    ativevaluest

    3]:

    hefinialvalu

    to

    o

    e.

  • 8/8/2019 Runge-Kutta Differential Equations

    7/25

    Gauss

    LeTheGaus

    numerica

    integratio

    domaino

    withinth

    And

    Wherea

    Thegene

    Wherec

    TwoPoi

    Forthet

    and1/sqr

    endre

    Form

    sLegendreF

    lly. Ittakest

    n.Itshould

    f[1,1],soif

    [1,1]doma

    isthelower

    alGaussLe

    arethewei

    tGaussLe

    opointmet

    t(3).Sothet

    Fig

    ulas

    rmulasprov

    heweighted

    enotedthat

    hedomaini

    in.Thischan

    boundofint

    endreFormu

    htsandxsa

    endreForm

    od,thewei

    opointme

    re5:FourthO

    ideaquicka

    sumoffuncti

    theGaussL

    outsideoft

    eofvariabl

    grationand

    lais[3]:

    rethepoints

    ula

    hts(cs)are

    hodtakesth

    rderRungeKut

    deasyway

    onvaluesat

    gendreFor

    isachange

    isaccomplis

    2

    2

    bistheupp

    wherethef

    all1,andthe

    isform:

    aMethod[7]

    tosolvethei

    specificpoin

    ulasareonl

    ofvariableis

    hedbyusing

    erboundof

    nctionisto

    functionist

    ntegrationof

    tswithinthe

    validwithin

    necessaryto

    thefollowin

    integration

    beevaluated

    obeevaluat

    functions

    domainof

    theintegrati

    fitthefuncti

    gformulas[3

    at.

    dat 1/sqrt(

    on

    on

    ]:

    )

  • 8/8/2019 Runge-Kutta Differential Equations

    8/25

    Thetwo

    FourPoi

    Thefour

    Plugging

    Thefourt

    ResultsInitiallyw

    ofthean

    ointmethod

    tGauss

    Le

    ointformul

    C0C1C2C3

    hesevaluesi

    hordergives

    eplottheta

    lyticalsoluti

    hasanappr

    endreFor

    hasthefoll

    eights

    .3478548

    .6521452

    .6521452

    .3478548Tabl

    ntothegene

    anapproxim

    safunction

    on. Thisplot

    ximateerro

    ula

    wingweight

    1:Fourpoint

    ralequation

    ateerrorof:

    oftime,and

    isasfollows:

    Figure6:Analy

    13 of:

    sandevalua

    aussLegendre

    willgivethe

    elocityasa

    ticSolutionoft

    3

    ionpoints:

    Ev

    X

    X1X

    XCoefficients[3]

    ourthorder

    functionofti

    heSystem

    luationPoin

    =.86113612

    =.33998104

    =.33998104

    3=.86113612]

    solution.

    metogivea

    ts

    generalesti

    ate

  • 8/8/2019 Runge-Kutta Differential Equations

    9/25

    Thisconfi

    lookatth

    Eachmet

    Eulerme

    Eulersm

    solution:

    Andwith

    solution:

    rmsthatthe

    eresultsobt

    hodisevalua

    hod

    thodwitha

    astepsizeo

    pendulumis

    inedfromth

    tedwithtwo

    stepsizeofh

    h=.05,Euler

    infactoscilla

    evariousnu

    stepsizes,h

    =.01yieldst

    Figure

    smethodyi

    tingbackan

    mericalmeth

    .05andh=.

    efollowing

    7:Euler.01Ste

    ldsthesere

    fourthwith

    odsdescribe

    1

    esults,plott

    p

    ults,againpl

    respecttoti

    dabove.

    dontopof

    ottedontop

    me.Wecan

    heanalytical

    oftheanaly

    now

    ical

  • 8/8/2019 Runge-Kutta Differential Equations

    10/25

    HeunsM

    Thismeththetrues

    results:

    ethod

    od,asstatedlopeofthef

    above,takenctionmore

    Figure

    thederivaticlosely.Heu

    8:Euler.05Ste

    veattwopoinsmethod

    p

    ntstomakeithaninter

    theextrapolalofh=.01yi

    tedslopefoleldsthefollo

    lowwing

  • 8/8/2019 Runge-Kutta Differential Equations

    11/25

    Withast

    psizeofh=.05,Heunsm

    Figure

    ethodyields

    Figure

    9:Heun.01Ste

    thefollowin

    10:Heun.05St

    p

    results:

    p

  • 8/8/2019 Runge-Kutta Differential Equations

    12/25

    MidpointMethod

    Withastepsizeofh=.01,theMidpointmethodreturnsthefollowingresults:

    Figure11:Midpoint.01StepAndwithastepofh=.05,theMidpointresultsare:

    0 0.5 1 1.5 2-4

    -3

    -2

    -1

    0

    1

    2

    3

    4Midpoint Angular Velocity Step Size=0.01

    Time (s)

    AngularVelocity(rad/sec

    0 0.5 1 1.5 2-0.8

    -0.6

    -0.4

    -0.2

    0

    0.2

    0.4

    0.6

    0.8Midpoint Angular Displacement Step Size=0.01

    Time (s)

    AngularDisplac

    ement(rad)

  • 8/8/2019 Runge-Kutta Differential Equations

    13/25

    Figure12:Midpoint.05Step

    FourthOrderRangeKutta

    Forastepsizeofh=.01,thefourthorderRangeKuttamethodreturnsthefollowingresults:

    Figure13:RK.01Step

    0 0.5 1 1.5 2-4

    -3

    -2

    -1

    0

    1

    2

    3

    4Midpoint Angular Velocity Step Size=0.05

    Time (s)

    AngularVelocity(rad/sec

    0 0.5 1 1.5 2-0.8

    -0.6

    -0.4

    -0.2

    0

    0.2

    0.4

    0.6

    0.8Midpoint Angular Displacement Step Size=0.05

    Time (s)

    AngularDisplacement(rad)

    0 0.5 1 1.5 2-4

    -3

    -2

    -1

    0

    1

    2

    3

    44th Order RK Angular Velocity Step Size=0.01

    Time (s)

    AngularVelocity(rad/sec

    0 0.5 1 1.5 2-1

    -0.8

    -0.6

    -0.4

    -0.2

    0

    0.2

    0.4

    0.6

    0.8

    14th Order RK Solution Angular Displacment Step Size=0.01

    Time (s)

    AngularDisplacement(rad)

  • 8/8/2019 Runge-Kutta Differential Equations

    14/25

    Andwithastepofh=.05

    Figure14:RK.05Step

    Finallywecanexaminethevaluesofeachofthemethodsatt=2,andcomparethesevalueswiththe

    integrationvaluesofequation(6)usingthetwoandfourpointGaussLegendreMethods:

    Method

    StepSize

    Velocity

    at

    t=2

    Analytical N/A 3.1054Euler 0.01 3.470153

    0.05 4.454886

    Heun 0.01 3.0405760.05 3.074375

    Midpoint 0.01 3.0407060.05 3.076673

    4thOrder

    RK

    0.01 3.1812530.05 3.726941

    TwoPointGauss N/A 9.800047FourPointGauss N/A 3.285373

    Table2:ComparisonofResultsatt=2

    0 0.5 1 1.5 2-4

    -3

    -2

    -1

    0

    1

    2

    3

    44th Order RK Angular Velocity Step Size=0.05

    Time (s)

    AngularVelocity(rad/sec

    0 0.5 1 1.5 2-1

    -0.8

    -0.6

    -0.4

    -0.2

    0

    0.2

    0.4

    0.6

    0.8

    14th Order RK Solution Angular Displacment Step Size=0.05

    Time (s)

    AngularDisplacement(rad)

  • 8/8/2019 Runge-Kutta Differential Equations

    15/25

    Discuss

    Uponexa

    derivativ

    numerica

    off. Roun

    thistype

    techniqu

    Lookinga

    accurate

    (highero

    andthere

    thelocal

    RungeKu

    errorsto

    larger. Lo

    ofthecur

    propagat

    Byincrea

    propagat

    ionminingthese

    stakenatm

    lmethodsto

    dofferrors

    ferrorcann

    susedtofin

    tthegeneral

    pproximatio

    der),theest

    foretheyva

    runcationer

    ttamethods

    pileup. Each

    okingatthe

    ve,buttend

    derror.

    ingtheorde

    derrorcan

    resultsitbe

    orepoints)a

    solvediffere

    reduetoth

    otbeeasilyc

    dvaluesofy.

    equationfor

    nsoftheslo

    imateforthe

    luesbecome

    ror.

    useprevious

    timeaniter

    resultssectio

    tostrayawa

    randthusth

    ereduced.

    Figur

    omesimme

    dasmaller

    ntialequatio

    limitations

    hanged. Tru

    thenumeric

    eresultin

    slopebeco

    moreaccura

    valuestoest

    tionofthen

    n,thisexplai

    fromtheex

    eaccuracyo

    onsiderthe

    15:Effectsof

    iatelyappar

    tepsizeresu

    sthereare

    fthecompu

    ncationerror

    almethodsu

    oreaccurate

    esmoreacc

    te. Soimpro

    imatenewv

    umericalme

    nswhythee

    actsolution

    theslope,a

    followinggr

    rderandStep

    entthathigh

    ltsinmorea

    wotypesof

    terwhende

    sarecaused

    sed(equatio

    yvalues. A

    ratewithre

    vingtheacc

    alues,soina

    thodoccurs

    stimatesare

    eartheend.

    dreducingt

    ph:

    SizeonError[8

    erorder(an

    ccurateresul

    errors,trunc

    alingwithsig

    bythenatur

    n(7)),itcan

    morepositi

    specttothe

    racyofeach

    curaciesino

    hiserrorget

    almostexact

    Thistypeof

    hestepsize

    ]

    therefore

    ts.Whenus

    tionandrou

    nificantdigit

    eofthe

    eseenthat

    nsareused

    xactsolutio

    yvaluedecr

    ldyvaluesc

    slargerand

    inthebegin

    erroriskno

    othlocalan

    ing

    nd

    and

    more

    ,

    ases

    use

    ing

    nas

    d

  • 8/8/2019 Runge-Kutta Differential Equations

    16/25

    TaketheEulermethodintheabovegraphasanexample. Becausethenextyvaluewillbebasedupon

    thatline,thecloserthatlineistothenexttruepoint,thebetterthenewyvaluewillbe. Itcanalsobe

    seenthatasthestepgrowslarger,theslopebecomesfartherfromtheexactsolution,socuttingstep

    sizecangreatlyimproveaccuracy. Byreducingthestepsizebyhalf,theglobalerrorforEulersmethod

    isalsohalved.

    Itisworthnotingthelocalandglobaltruncationerrorforeachofthenumericalmethods:

    Method LocalError GlobalErrorEuler O(h2) O(h)

    Heun O(h3) O(h2)

    Midpoint O(h3) O(h2)

    4thOrderRK O(h5) O(h4)Table3:ComparisonofError[3]

    WhatthistableessentiallyshowsisthatadecreaseinstepsizewillcausetheHeun/Midpoint/fourth

    ordermethodstodecreaseinerroratafasterratethanEulersmethod

    Conclusion

    Ascanbeseenfromtheaboveresults,therearemanymethodsthatcanbeusedtosolveacoupled

    systemofequations. Allofthesemethodshavetheirtradeoffswhencomparedtoeachother. Eulers

    methodisrelativelyinaccurate,butitisnotintensiveoncomputerresourcesanditiseasiertoprogram.

    ThefourthorderRungeKuttaisthemostaccurateofthemethodsexamined,butitcanbetaxingon

    systemresourcesandismorelaborintensivetoprogram. Thisiswhyonemethodcannotbefavored

    overanother,anditisimportanttoassesswhatisneededfromtheoutput;accuracyorlowtime/money

    investment.

    References

    [1]"Molecularvibration Wikipedia,thefreeencyclopedia."Wikipedia,thefreeencyclopedia.N.p.,n.d.Web.15Nov.2010..

    [2]Drapaca,Corina.Project3:NumericalAnalysisoftheSwingingSimplePendulum.PennsylvaniaStateUniversity,2010.Print.

    [3]Chapra,StevenC.,andRaymondP.Canale.Numericalmethodsforengineers.6thed.Boston:McgrawHillHigherEducation,2010.Print.

    [4]"Euler'sMethodforFirstOrderDifferentialEquations."Swarthmore.N.p.,n.d.Web.15Nov.2010.

    .

  • 8/8/2019 Runge-Kutta Differential Equations

    17/25

    [5]"NumericalTutorials:Euler'sMethod."ComputerEngineering,ChulalongkornUniversity.N.p.,n.d.Web.15Nov.2010..

    [6]"MidpointMethod."Wikipedia,thefreeencyclopedia.N.p.,n.d.Web.15Nov.2010..

    [7]"ODE2:RungeKutta."BostonCollegePhysics.N.p.,n.d.Web.15Nov.2010..

    [8]"Runge Kutta."DrexelUniversity:DepartmentofPhysics:Home.N.p.,n.d.Web.15Nov.2010..

    Appendix

    Variables

    ti=0;

    tf=2;

    theta(1)=pi/4;

    v(1)=0;

    g=32.2;

    L=2;

    Eulers

    %Set the step size and number of calculations

    h=.01;

    nc=(tf-ti)/h+1;

    %Euler's algorithm

    for i=2:nc

    theta(i) = theta(i-1) +v(i-1)*h;

    v(i) = v(i-1) + - g/L *sin(theta(i-1))*h;

    end

    fprintf('\nThe velocity at t=2 by the Euler Method with step-size 0.01 is %f

    \n\n', v(i))

    %graphing results

    t=0:0.01:2;

    figure

    hold on, subplot(1,2,2), plot(t,v,'r');

    title('Eulers Angular Velocity Step Size=0.01')

    xlabel('Time (s)')

    ylabel('Angular Velocity (rad/sec')

    grid on

    hold on, subplot(1,2,1), plot(t,theta,'r');

    title('Eulers Angular Displacement Step Size=0.01')

    xlabel('Time (s)')

    ylabel('Angular Displacement (rad)')

  • 8/8/2019 Runge-Kutta Differential Equations

    18/25

    grid on

    for i = 1:201

    position(i) = pi/4*cos(sqrt(g/L)*t(i));

    velocity(i) = -sqrt(g/L)*(pi/4)*sin(sqrt(g/L)*t(i));

    end

    hold on, subplot(1,2,1), plot(t,position,'b');

    hold on, subplot(1,2,2), plot(t,velocity,'b');

    %Euler's Method (h=0.05)

    clear all

    %For Equations (5)n and (6)

    %Initialize variables

    ti=0;

    tf=2;theta(1)=pi/4;

    v(1)=0;

    g=32.2;

    L=2;

    %Set the step size and number of calculations

    h=.05;

    nc=(tf-ti)/h+1;

    %Euler's algorithm

    for i=2:nc

    theta(i) = theta(i-1) +v(i-1)*h;

    v(i) = v(i-1) + - g/L *sin(theta(i-1))*h;

    end

    fprintf('\nThe velocity at t=2 by the Euler Method with step-size 0.05 is %f

    \n\n', v(i))

    %graphing results

    t=0:0.05:2;

    figure

    hold on, subplot(1,2,2), plot(t,v,'r');

    title('Eulers Angular Velocity Step Size=0.05')

    xlabel('Time (s)')

    ylabel('Angular Velocity (rad/sec')grid on

    hold on, subplot(1,2,1), plot(t,theta,'r');

    title('Eulers Angular Displacement Step Size=.05')

    xlabel('Time (s)')

    ylabel('Angular Displacement (rad)')

    grid on

    for i = 1:41

    position(i) = pi/4*cos(sqrt(g/L)*t(i));

  • 8/8/2019 Runge-Kutta Differential Equations

    19/25

    velocity(i) = -sqrt(g/L)*(pi/4)*sin(sqrt(g/L)*t(i));

    end

    hold on, subplot(1,2,1), plot(t,position,'b');

    hold on, subplot(1,2,2), plot(t,velocity,'b');

    Heuns

    %Initialize variablesti=0;

    tf=2;

    theta(1)=pi/4;

    v(1)=0;

    g=32.2;

    L=2;

    %Set the step size and number of calculations

    h=.01;

    nc=(tf-ti)/h+1;

    %Heun's algorithm

    for i=2:ncthetap(i) = theta(i-1) +v(i-1)*h;

    vp(i) = v(i-1) + - g/L *sin(theta(i-1))*h;

    theta(i) = theta(i-1) + (vp(i)+v(i-1))/2*h;

    v(i) = v(i-1) + (-g/L*sin(theta(i-1))+(-g/L*sin(thetap(i))))/2*h;

    end

    fprintf('\nThe velocity at t=2 by the Heun Method with step-size 0.01 is %f

    \n\n', v(i))

    %graphing results

    t=0:0.01:2;

    figurehold on, subplot(1,2,2), plot(t,v,'r');

    title('Heuns Angular Velocity Step Size =0.01)')

    xlabel('Time (s)')

    ylabel('Angular Velocity (rad/sec')

    grid on

    hold on, subplot(1,2,1), plot(t,theta,'r');

    title('Heuns Angular Displacment Step Size=0.01')

    xlabel('Time (s)')

    ylabel('Angular Displacement (rad)')

    grid on

    for i = 1:201

    position(i) = pi/4*cos(sqrt(g/L)*t(i));

    velocity(i) = -sqrt(g/L)*(pi/4)*sin(sqrt(g/L)*t(i));end

    hold on, subplot(1,2,1), plot(t,position,'b');

    hold on, subplot(1,2,2), plot(t,velocity,'b');

  • 8/8/2019 Runge-Kutta Differential Equations

    20/25

    %Heun's Method (h=0.05)

    clear all

    %For Equations (5) and (6)

    %Initialize variables

    ti=0;

    tf=2;

    theta(1)=pi/4;

    v(1)=0;

    g=32.2;

    L=2;

    %Set the step size and number of calculations

    h=.05;

    nc=(tf-ti)/h+1;

    %Heun's algorithm

    for i=2:ncthetap(i) = theta(i-1) +v(i-1)*h;

    vp(i) = v(i-1) + - g/L *sin(theta(i-1))*h;

    theta(i) = theta(i-1) + (vp(i)+v(i-1))/2*h;

    v(i) = v(i-1) + (-g/L*sin(theta(i-1))+(-g/L*sin(thetap(i))))/2*h;

    end

    fprintf('\nThe velocity at t=2 by the Heun Method with step-size 0.05 is %f

    \n\n', v(i))

    %graphing results

    t=0:0.05:2;

    figure

    hold on, subplot(1,2,2), plot(t,v,'r');

    title('Heuns Angular Velocity Step Size=0.05)')

    xlabel('Time (s)')

    ylabel('Angular Velocity (rad/sec')

    grid on

    hold on, subplot(1,2,1), plot(t,theta,'r');

    title('Heuns Angular Displacment Step Size=0.05)')

    xlabel('Time (s)')

    ylabel('Angular Displacement (rad)')

    grid on

    for i = 1:41

    position(i) = pi/4*cos(sqrt(g/L)*t(i));velocity(i) = -sqrt(g/L)*(pi/4)*sin(sqrt(g/L)*t(i));

    end

    hold on, subplot(1,2,1), plot(t,position,'b');

    hold on, subplot(1,2,2), plot(t,velocity,'b');

  • 8/8/2019 Runge-Kutta Differential Equations

    21/25

    Midpoint

    ti=0;

    tf=2;

    theta(1)=pi/4;

    v(1)=0;

    g=32.2;

    L=2;

    %Set the step size and number of calculations

    h=.01;

    nc=(tf-ti)/h+1;

    %Midpoint algorithm

    for i=2:nc

    thetap(i) = theta(i-1) +v(i-1)*h/2;

    vp(i) = v(i-1) + - g/L *sin(theta(i-1))*h/2;

    theta(i) = theta(i-1) + vp(i)*h;

    v(i) = v(i-1) + (-g/L*sin(thetap(i)))*h;

    end

    fprintf('\nThe velocity at t=2 by the Midpoint Method with step-size 0.01 is

    %f \n\n', v(i))

    %graphing results

    t=0:0.01:2;

    figure

    hold on, subplot(1,2,2), plot(t,v,'r');

    title('Midpoint Angular Velocity Step Size=0.01')

    xlabel('Time (s)')

    ylabel('Angular Velocity (rad/sec')

    grid onhold on, subplot(1,2,1), plot(t,theta,'r');

    title('Midpoint Angular Displacement Step Size=0.01')

    xlabel('Time (s)')

    ylabel('Angular Displacement (rad)')

    grid on

    for i = 1:201

    position(i) = pi/4*cos(sqrt(g/L)*t(i));

    velocity(i) = -sqrt(g/L)*(pi/4)*sin(sqrt(g/L)*t(i));

    end

    hold on, subplot(1,2,1), plot(t,position,'b');

    hold on, subplot(1,2,2), plot(t,velocity,'b');

    %Midpoint Method (h=0.05)

    clear all

  • 8/8/2019 Runge-Kutta Differential Equations

    22/25

    %For Equations (5) and (6)

    %Initialize variables

    ti=0;

    tf=2;

    theta(1)=pi/4;

    v(1)=0;

    g=32.2;

    L=2;

    %Set the step size and number of calculations

    h=.05;

    nc=(tf-ti)/h+1;

    %Midpoint algorithm

    for i=2:nc

    thetap(i) = theta(i-1) +v(i-1)*h/2;

    vp(i) = v(i-1) + - g/L *sin(theta(i-1))*h/2;

    theta(i) = theta(i-1) + vp(i)*h;

    v(i) = v(i-1) + (-g/L*sin(thetap(i)))*h;

    end

    fprintf('\nThe velocity at t=2 by the Midpoint Method with step-size 0.05 is

    %f \n\n', v(i))

    %graphing results

    t=0:0.05:2;

    figure

    hold on, subplot(1,2,2), plot(t,v,'r');

    title('Midpoint Angular Velocity Step Size=0.05')

    xlabel('Time (s)')

    ylabel('Angular Velocity (rad/sec')

    grid on

    hold on, subplot(1,2,1), plot(t,theta,'r');

    title('Midpoint Angular Displacement Step Size=0.05')

    xlabel('Time (s)')

    ylabel('Angular Displacement (rad)')

    grid on

    for i = 1:41

    position(i) = pi/4*cos(sqrt(g/L)*t(i));

    velocity(i) = -sqrt(g/L)*(pi/4)*sin(sqrt(g/L)*t(i));

    end

    hold on, subplot(1,2,1), plot(t,position,'b');hold on, subplot(1,2,2), plot(t,velocity,'b');

  • 8/8/2019 Runge-Kutta Differential Equations

    23/25

    FourthOrderRK

    ti=0;

    tf=2;

    theta(1)=pi/4;

    v(1)=0;

    g=32.2;L=2;

    %Set the step size and number of calculations

    h=.01;

    nc=(tf-ti)/h+1;

    %4th Order RK algorithm

    for i=2:nc

    vp(i-1)=v(i-1)+2*(-g/L*sin(theta(i-1))*h/2);

    thetap(i-1)=theta(i-1)+vp(i-1)*h/2;

    vpp(i-1)=v(i-1)+(-g/L*sin(thetap(i-1))*h/2);thetapp(i-1)=theta(i-1)+vpp(i-1)*h;

    vppp(i-1)=v(i-1)+(-g/L*sin(thetapp(i-1))*h);

    theta(i)=theta(i-1)+1/6*h*(v(i-1)+2*vp(i-1)+2*vpp(i-1)+vppp(i-1));

    v(i)=v(i-1)+(-g/L*sin(theta(i-1))*h);

    end

    fprintf('\nThe velocity at t=2 by the 4th order Runge-Kutta Method with step-

    size 0.01 is %f \n\n', v(i))

    %graphing results

    t=0:0.01:2;

    figure

    hold on, subplot(1,2,2), plot(t,v,'r');

    title('4th Order RK Angular Velocity Step Size=0.01')

    xlabel('Time (s)')

    ylabel('Angular Velocity (rad/sec')

    grid on

    hold on, subplot(1,2,1), plot(t,theta,'r');

    title('4th Order RK Solution Angular Displacment Step Size=0.01')

    xlabel('Time (s)')

    ylabel('Angular Displacement (rad)')

    grid on

    for i = 1:201position(i) = pi/4*cos(sqrt(g/L)*t(i));

    velocity(i) = -sqrt(g/L)*(pi/4)*sin(sqrt(g/L)*t(i));

    end

    hold on, subplot(1,2,1), plot(t,position,'b');

    hold on, subplot(1,2,2), plot(t,velocity,'b');

  • 8/8/2019 Runge-Kutta Differential Equations

    24/25

    %4th order RK Method (h=0.05)

    clear all

    %For Equations (5) and (6)

    %Initialize variables

    ti=0;

    tf=2;

    theta(1)=pi/4;

    v(1)=0;

    g=32.2;

    L=2;

    %Set the step size and number of calculations

    h=.05;

    nc=(tf-ti)/h+1;

    %4th Order RK algorithm

    for i=2:nc

    vp(i-1)=v(i-1)+2*(-g/L*sin(theta(i-1))*h/2);thetap(i-1)=theta(i-1)+vp(i-1)*h/2;

    vpp(i-1)=v(i-1)+(-g/L*sin(thetap(i-1))*h/2);

    thetapp(i-1)=theta(i-1)+vpp(i-1)*h;

    vppp(i-1)=v(i-1)+(-g/L*sin(thetapp(i-1))*h);

    theta(i)=theta(i-1)+1/6*h*(v(i-1)+2*vp(i-1)+2*vpp(i-1)+vppp(i-1));

    v(i)=v(i-1)+(-g/L*sin(theta(i-1))*h);

    end

    fprintf('\nThe velocity at t=2 by the 4th order Runge-Kutta Method with step-

    size 0.05 is %f \n\n', v(i))

    %graphing results

    t=0:0.05:2;

    figure

    hold on, subplot(1,2,2), plot(t,v,'r');

    title('4th Order RK Angular Velocity Step Size=0.05')

    xlabel('Time (s)')

    ylabel('Angular Velocity (rad/sec')

    grid on

    hold on, subplot(1,2,1), plot(t,theta,'r');

    title('4th Order RK Solution Angular Displacment Step Size=0.05')

    xlabel('Time (s)')

    ylabel('Angular Displacement (rad)')

    grid on

    for i = 1:41

    position(i) = pi/4*cos(sqrt(g/L)*t(i));

    velocity(i) = -sqrt(g/L)*(pi/4)*sin(sqrt(g/L)*t(i));

    end

    hold on, subplot(1,2,1), plot(t,position,'b');

    hold on, subplot(1,2,2), plot(t,velocity,'b');

  • 8/8/2019 Runge-Kutta Differential Equations

    25/25