ComputerModelsofProcessDynamics
FromNewtontoEnergyFields
OlisRubin
Brooklyn,Pretoria,SouthAfrica
Copyright©2023byTheInstituteofElectricalandElectronicsEngineers,Inc.Allrightsreserved.
PublishedbyJohnWiley&Sons,Inc.,Hoboken,NewJersey. PublishedsimultaneouslyinCanada.
Nopartofthispublicationmaybereproduced,storedinaretrievalsystem,ortransmittedin anyformorbyanymeans,electronic,mechanical,photocopying,recording,scanning,or otherwise,exceptaspermittedunderSection107or108ofthe1976UnitedStatesCopyrightAct, withouteitherthepriorwrittenpermissionofthePublisher,orauthorizationthroughpaymentof theappropriateper-copyfeetotheCopyrightClearanceCenter,Inc.,222RosewoodDrive, Danvers,MA01923,(978)750-8400,fax(978)750-4470,oronthewebatwww.copyright.com. RequeststothePublisherforpermissionshouldbeaddressedtothePermissionsDepartment, JohnWiley&Sons,Inc.,111RiverStreet,Hoboken,NJ07030,(201)748-6011,fax(201)748-6008, oronlineathttp://www.wiley.com/go/permission.
LimitofLiability/DisclaimerofWarranty:Whilethepublisherandauthorhaveusedtheirbest effortsinpreparingthisbook,theymakenorepresentationsorwarrantieswithrespecttothe accuracyorcompletenessofthecontentsofthisbookandspecificallydisclaimanyimplied warrantiesofmerchantabilityorfitnessforaparticularpurpose.Nowarrantymaybecreatedor extendedbysalesrepresentativesorwrittensalesmaterials.Theadviceandstrategiescontained hereinmaynotbesuitableforyoursituation.Youshouldconsultwithaprofessionalwhere appropriate.Neitherthepublishernorauthorshallbeliableforanylossofprofitoranyother commercialdamages,includingbutnotlimitedtospecial,incidental,consequential,orother damages.
Forgeneralinformationonourotherproductsandservicesorfortechnicalsupport,pleasecontact ourCustomerCareDepartmentwithintheUnitedStatesat(800)762-2974,outsidetheUnited Statesat(317)572-3993orfax(317)572-4002.
Wileyalsopublishesitsbooksinavarietyofelectronicformats.Somecontentthatappearsinprint maynotbeavailableinelectronicformats.FormoreinformationaboutWileyproducts,visitour websiteatwww.wiley.com.
LibraryofCongressCataloging-in-PublicationDataAppliedfor
ISBN:9781119885658[Hardback]
CoverDesign:Wiley
CoverImages:©zhengshuntang/GettyImages;CourtesyofOlisRubin
Setin9.5/12.5ptSTIXTwoTextbyStraive,Pondicherry,India
ToJudy
Shebroughtbeauty,goodnessandloveinmylife. Wegivethanksforalltheblessingsthatwehavereceived,togetherwithourchildren
Contents
Preface xiii
1Introduction 1
1.1Engineeringusesofcomputermodels 1
1.1.1 Missionstatement 2
1.2Thesubjectmatter 3
1.3Mathematicalmaterial 4
1.4Someremarks 5 Bibliography 5
2FromComputerHardwaretoSoftware 7
2.1Introduction 7
2.2 Comp utingmachines 7
2.2.1Thesoftwareinterface 8
2.3Computerprogramming 9
2.3.1Algebraicexpressions 10
2.3.2Mathfunctions 13
2.3.3Computationloops 14
2.3.4Decisionmaking 16
2.3.5Graphics 17
2.3.6Userdefinedfunctions 17
2.4Statetransitionmachines 17
2.4.1Abinarysignalgenerator 18
2.4.2Operationalcontrolofanindustrialplant 24
2.5Differenceengines 25
2.5.1Differenceequationtocalculatecompoundinterest 26
2.6Iterativeprogramming 27
2.6.1Inversefunctions 29
2.7Digitalsimulationofdifferentialequations 30
2.7.1Rectangularintegration 31
2.7.2Trapezoidalintegration 33
2.7.3Second-orderintegration 35
2.7.4AnExample 36
2.8Discussion 37 Exercises 38 References 41
3Creativethinkingandscientifictheories 43
3.1Introduction 43
3.2 The dawnofastronomy 44
3.3Therenaissance 45
3.3.1Galileo 45
3.3.2Newton 46
3.4Electromagnetism 49
3.4.1Magneticfields 50
3.4.2Electromagneticinduction 50
3.4.3Electromagneticradiation 51
3.5Aerodynamics 52
3.5.1Vectorflowfields 53
3.6Discussion 54 References 56
4Calculusandthecomputer 57
4.1Introduction 57
4.2 Mathematicalsolutionofdifferentialequations 58
4.3Fromphysicalanalogstoanalogcomputers 60
4.4Picard’smethodforsolvinganonlineardifferentialequation 61
4.4.1MechanizationofPicard’smethod 62
4.4.2Feedbackmodelofthedifferentialequation 62
4.4.3ApproximatesolutionbyTaylorseries 64
4.5Exponentialfunctionsandlineardifferentialequations 65
4.5.1Taylorseriestoapproximateexponentialfunctions 66
4.6Sinusoidalfunctionsandphasors 67
4.6.1Taylorseriestoapproximatesinusoids 69
4.7Bessel’sequation 70
4.8Discussion 72 Exercises 73 Bibliography 74
5Scienceandcomputermodels 75
5.1Introduction 75
5.2 A planetaryorbitaroundastationarySun 76
5.2.1Ananalyticsolutionforplanetaryorbits 79
5.2.2Adifferenceequationtomodelplanetaryorbits 80
5.3Simulationofaswingingpendulum 81
5.3.1Agraphicalconstructiontoshowthemotionofapendulum 83
5.3.2Truncationandroundofferrors 84
5.4Lagrange’sequationsofmotion 85
5.4.1Adoublependulum 87
5.4.2Afewcomments 90
5.4.3Modesofmotionofadoublependulum 90
5.4.4Structuralvibrationsinanaircraft 91
5.5Discussion 94 Exercises 94 Bibliography 95
6Flightsimulators 97
6.1Introduction 97
6.2 The motionofanaircraft 98
6.2.1Theequationsofmotion 99
6.3Shortperiodpitchingmotion 101
6.3.1Casestudyofshortperiodpitchingmotion 104
6.3.2Stateequationsofshortperiodpitching 105
6.3.3Transferfunctionsofshortperiodpitching 107
6.3.4Frequencyresponseofshortperiodpitching 108
6.4Phugoidmotion 110
6.5Userinterfaces 111
6.6Discussion 112 Exercises 113 Bibliography 114
7Finiteelementmodelsandthediffusionofheat 115
7.1Introduction 115
7.2 A thermalmodel 117
7.2.1Afiniteelementmodelbasedonanelectricalladdernetwork 118
7.2.2Freesettlingfromaninitialtemperatureprofile 119
7.2.3Stepresponsetest 121
7.2.4Statespacemodelofdiffusion 126
7.3Apracticalapplication 129
7.4Two-dimensionalsteady-statemodel 131
7.5Discussion 132
Exercises 134
Bibliography 135
8Waveequations 137
8.1Introduction 137
8.2 Energy storagemechanisms 138
8.2.1Partialdifferentialequationdescribingpropagationinatransmission line 140
8.3Afiniteelementmodelofatransmissionline 141
8.4Statespacemodelofastandingwaveinavibratingsystem 145
8.4.1Statespacemodelofamultiplecompoundpendulum 147
8.5Atwo-dimensionalelectromagneticfield 148
8.6Atwo-dimensionalpotentialflowmodel 151
8.7Discussion 155
Exercises 156
Bibliography 159
9Uncertaintyandsofterscience 161
9.1Introduction 161
9.2 Empirical and “blackbox” models 162
9.2.1Animperfectmodelofasimplephysicalobject 163
9.2.2Finiteimpulseresponsemodels 164
9.3Randomnesswithincomputermodels 166
9.3.1Randomnumbergeneratorsanddataanalysis 167
9.3.2Statisticalestimationandthemethodofleastsquares 168
9.3.3Astateestimator 171
9.3.4Avelocityestimator 175
9.3.5AnFIRfilter 176
Bibliography 196 x Contents
9.4Economic,Geo-,Bio-,andothersciences 179
9.4.1Apricingstrategy 181
9.4.2Theproductivityofmoney 184
9.4.3Commentsonbusinessmodels 187
9.5Digitalimages 189
9.5.1Animageprocessor 190
9.6Discussion 193
Exercises 194
10Computermodelsinadevelopmentproject 197
10.1Introduction 197
10.1.1 The scopeofthischapter 198
10.2Amotordrivemodel 198
10.2.1Aconceptualmodel 200
10.2.2Themotordriveparameters 202
10.2.3Creatingthesimulationmodel 203
10.2.4Theelectricalandmechanicalsubsystems 204
10.2.5Systemintegration 206
10.2.6Configurationmanagement 208
10.3Thedefinitionphase 208
10.3.1Selectionofthemotor 209
10.3.2Simulationofloaddisturbances 210
10.4Thedesignphase 213
10.4.1Calculationoffrequencyresponse 213
10.4.2Thecurrentcontrolloop 214
10.4.3Designreviewandfurtheractions 217
10.4.4Ratefeedback 219
10.5Asetbacktotheproject 222
10.5.1Elasticcouplingbetweenmotorandload 222
10.6Discussion 227 Exercises 229 Bibliography 230
11Postscript 231
11.1Lookingback 231
11.2 The operationofasimulationfacility 233
11.3Lookingforward 234 Bibliography 235
AppendixAFrequencyresponsemethods 237
Appendix BVectoranalysis 261
AppendixCScalarandvectorfields 269
AppendixDProbabilityandstatisticalmodels 287 Index 297
Preface
“Itisunworthyforexcellentmentolosehourslikeslavesinthelaborof calculationwhichcouldsafelyberelegatedtoanyoneelseifmachines wereused”
GottfriedWilhelmLeibniz(1685)
MyfirstjobwaswithalargeelectricalengineeringenterprisewhereIhadbeen movedtoadivisionthatdesignedandinstalledheavydutymotordrives.Our divisionhadjustacquiredananalogcomputerthatwasbarelylargeenoughto simulatethesemachines.IwasluckytobechosentoworkwithmyfriendGopal toseewhatwecouldachievewiththis “new-fangledcontraption.” Ourfirstproject wastoinvestigatetheperformanceofaWard-Leonard(generator–motor)setthat droveahugeminingmachine.Thecomputergaveusanew “windowtothe world,” throughwhichwecouldseewhatwashappeninginsidethemotor.All thatwehadlearnedasundergraduatesnowfellintoplace.Ourbasictraining hadconsideredthesteadystateoperationofelectricmotors,whilethelectures ondynamicbehaviorwereentirelymathematical.Wecouldnowconstructacomputermodelthatallowedustoseethehardware,thedifferentialequations,and thetransientbehaviorofshaftsandothervariables.Thisiswhatacomputermodel candoforus!
Leibnizwouldhavebeenelatedifhecouldhaveforeseenhowfarmachines couldtakeus,beyondjustsavinguslaboriouscalculations.Digitalcomputers nowprovideuswithplatformsthatmakethephysicalmodelingprocessalmost effortless,leavingusfreetothinkaboutmoreimportantquestions.Thisbookis writtentoshowhowacomputercanbeprogrammedtosimulatemotionin general.Wewillnotincludethegrowingmarketfornewuserinterfaces,such asvirtualrealityornetworking.Thesefieldsshouldbelefttotheexpertattention ofspecialists.
Inadditiontosettingthewheelsinmotionalongapaththatledtothecomputers oftoday,Leibnizwasalsotheco-founderofdifferentialcalculus.Thecreationofa dynamicmodelisdeeplyrootedinmathematicalanalysis.Wewillsacrificetheoreticalrigorinordertosimplifythemathematicsinawaythatisintelligibletothe workingengineerandcomputerprofessional.Whereverpossiblewewillexplain mathematicaloperationsbymeansofcomputerprogramsthatapproximatetheir behavior.
Thanksgotothemanyreviewerswhosesuggestionshelpedtobringthisbook intoitspresentform.Ihopethatitwillgivereadersthebenefitofexperiencethat wasgainedbyworkingwithmanycolleaguesondiverseprojects.ThankstoPhilip deVaal,whoseenthusiasticsupportstrengthenedmetopersevereinthefaceof setbacks,andtoBeckervanNiekerk,whoseindustryconstantlyinvigoratedme tocompletethisproject.ThisisthesecondtimethatAileenStorryhashelped mebringabooktoseethelightofday.ThankstotheprofessionalismoftheWiley team,ledbyKimberly,MustaqandPatricia,thatmanagedthepublicationprocess.
Imustthankmydearestwifeforherconstant,unstintingsupport.Notonlyis herspellingbetterthanmine,butshehasawayofprovokingmetowritemore lucidlyforyou,thereader.Mayitthusgiveyoufoodforthought,andbetterequip youforthefuture!
xiv Preface
1.1Engineeringusesofcomputermodels
Computermodelsareusedthroughouteveryphaseofindustrialresearch, design,anddevelopment.Simulationstudiescanplayalargepartintheconcept phaseofanengineeringprojectsinceco mputermodelscanusuallybecreatedin lesstimeandcostlessthanhardwareprototypes.Theverycreationofsuchmodelsforceseveryonetodelvedeeperintotheunderlyingphysicsoftheplant.This cangivevaluableinsightintoplantoperationthatcanaidtheplantdesigners.If suchsimulatorsaredevelopedbeforetheplantisbuilt,theycanbeusedtoevaluatethedesignbeforeexpensivedecisionsaremade,andtherebyhelptoavoid costlymistakes.Inthelaterstagesofa developmentprogram,wecangreatly reducethetimeandcostofcommissioningandqualificationbyusingsimulator studiestoreducethescaleofhardwaretesting.Themodelcanalsobeusedto determinesafetylimitsandemergencyproceduresbysimulatingteststhatwould behazardousintherealplant.Thereisalsoagrowingmarketfortrainingsimulatorstoensurethecompetenceoftheoperatorswhowillruntheplant.Wecan foreseethatthiswilltieupwiththecreationofvirtualrealityandthecomputer gameindustry.
Computermodelingofdynamicprocesseshasalongassociationwithcontrol engineering,wherethereisoftenaninterestinthespeedwithwhichthesystem settlestoarequiredoperatingcondition.Thedesignersgenerallymakeuseof feedbackcontrolloops,wheretheyhavetoallowforthetimeresponseofthe planttocontrolinputs.Computermodelswereusedtostudysimpleservomechanisms,andthisledtotheirextensiv euseinverylargeandcomplexfeedback controlproblems.Theyhavebeenwidelyemployedintheaerospaceindustry forthedesignofflightcontrolsystems.Theprocesscontrolindustryhas appliedcomputermodelingtosuchlarge-scalestudiesasoptimizingacomplete
ComputerModelsofProcessDynamics:FromNewtontoEnergyFields,FirstEdition. OlisRubin.
©2023TheInstituteofElectricalandElectronicsEngineers,Inc. Published2023byJohnWiley&Sons,Inc.
chemicalprocess.Thegrowingfieldofroboticswillalsomakeuseofdynamic models.
“Thepurposeofcomputingisinsight,notnumbers.”
R.W.Hamming(1962)
Computermodelsalsofindapplicationinmanydiversescientificfields,includingareasthatareknownasthesoftersciences.Asweusemachinerytoperform manuallabor,wecanusecomputerstomechanizedifficultrepetitivemathematicalprocessesandtherebyfreeourmindstoconsiderquestionsofamoreintellectualnature.
1.1.1Missionstatement
Thisbookiswrittenforyou,theprofessionalworkerinthefieldofcomputermodeling,whowishestowidenyourhorizonandneedstoconsidernewapproaches, applications,andadvancedtechniques.Whenweusetheword “model” weare thinkingofaprogramthatsimulatesthedynamicbehaviorofaphysicalphenomenon.Perhapsyouhavenotalreadyenteredthefield,butwishtoapplyyourtraininginappliedmathematicsandexperiencewithcomputerstoexplorethebehavior ofanobjectthatevolvesinthisway.Thisbookproceedsfrombasicmethodsof programmingandsetsupmathematicalmodelsoffairlycommonobjectsthat canbedescribedbyreasonablysimpleequations.
Aseriesofcasestudiescoversamyriadofdifferenttopicsinordertoprovidea vistaofthechallengesthatfallwithinthisdiscipline.Thesetopicshavebeenfitted intoaframeworkthatprogressesfromintroductorymaterialtosubjectsofincreasingcomplexity.Youwillmeetscoresofexamplesthathavebeencarefullychosen totakeyoustepbystepalongalogicallearningcurvethatleadstogreater enlightenment.
Itisshownhowthecomputerhasprogressedfrombeingameretooltoconvert mathematicalequationsintonumbers.Wecaninteractwithitaswithvirtualrealitywhereitsgraphicaloutputmakestheequationsbecomealive.
Thereisanothermissiontobeaccomplished.Ifthereistobesynergybetween yourselfandthecomputer,thesimulationprocesshastostandfirmlyonthefollowinglegs:
1.2Thesubjectmatter
Thebookprovidesalongseriesofcasestudiesthatarebasedonpersonalexperience. Theemphasisisonthesimulationofmovingobjectsorthepropagationofenergyin aphysicalmedium.Computermodelsarepresentedtothereadereitherasprogram listingsorasblockdiagrams.MostofthemareprogrammedontheMATLAB® or Scilab® platforms:
MATLABisaregisteredtrademarkofTheMathWorks,Inc.
ScilabisregisteredundertheGPLv2license(previouslyCeCILL)ascirculatedby CEA,CNRS,andInria.
ThecomputercodefragmentsusestatementsthatareeasilyunderstoodbyPython andCusers.
Chapter2 givesanintroductiontocomputerprogramming,usingtheinstructionsetsfromMATLABandScilab.Thisfirstlyshowshowtoperformvarious repetitiveoperations,andthengoesontoconsidertheuseofadigitalcomputer tosimulatedifferentialequations.Thesetechniqueswillserveasaspringboard forthecreationofeventhemostadvancedcomputermodels.
Chapter3 servesasanobjectlessontoshowhowcreativethinkingisatoolin themodelbuildingprocess.Itexplainshowscientifictheoriesareactuallyconceptualmodelsthatdescribephysicalphenomenaandshowshowtheevolutionof sciencedependedonaseriesofinspiredguesses.Itdescribesthedevelopment ofthreedifferentmathematicalframeworksthatareusedinlaterchapterstoillustratethecreationofvariouscomputermodels.
Chapter4 showshowdifferentialequationscanbeimplementedascomputer models,whichcanthenbeexploitedtoproducegraphsandnumbers.Italsoshows howmathematicaltoolsbasedoncalculuscanbeusedtofindanalyticalsolutions thatsatisfytheequations.Ittherebyillustrateshowproblemscanbestudiedby twoindependentmethodstoincreaseourconfidenceintheresults.
Chapter5 considersthecreationofdifferentialequationsthatdescribethe motionofpointmassesandtheirimplementationascomputermodels.Italsoshows howanalyticalsolutionscanbeusedtoperformcross-checks,toverifythecomputed results.
Chapter6 thenconsidersthemotionofarigidbodyandthecreationofaflight simulatorintheaircraftindustry.
Chapter7 analysestheflowofheatthroughasolidbodybyexploitingmathematicalmethodsthatarebasedontheconceptofscalarandvectorfields.Theseare usedtoshowhowtheevolutionofatemperaturefieldcanbedescribedbyapartial differentialequation.Itisdemonstratedhowacomputermodelcanbecreatedby 1.2Thesubjectmatter
approximatingthebodyasaseriesoffiniteelements,whereeachindividual elementcanbedescribedbyanordinarydifferentialequation.
Chapter8 analyseswavepropagationofanenergyfieldthroughacontinuous medium.Itagaindemonstrateshowacomputermodelcanbecreatedbyapproximatingthemediumasaseriesoffiniteelements.Methodsareusedthatare similartothosedescribedinChapter7.Theanalysisofthephysicalphenomena discussedinthesetwochaptersismuchmorecomplexthanthestudyofmechanicalmotion.Thecasestudiesuseacombinationofcomputermodeling,mathematicalanalysis,andphysicalanalogiesasawaytogainabetterunderstandingofthe physicalprocessesthatareconsidered.
Chapter9 widensourhorizonbyexploringtherealmofuncertaintyandstatisticalanalysis.Theexamplesthatappearinthischapterconsidervarioustopics, whichrangefromimperfecttheoreticalknowledgetomeasurementnoise,aswell asbusinessmodelsanddigitalimages.
Chapter10 showshowsimulationengineerscanworkasmembersofadesign teamwithinanengineeringproject.Atthebeginningoftheprojectthecomputer modelcanbeusedasanelectronicprototypethatiscreatedmorequicklyand cheaplythanhardware.Italsoprovidesthefacilityforcheckingthesensitivity oftheproducttovariationsinparameterswithinthedesigntolerances.Theremust beaconfigurationmanagementprocesstokeeptrackofchangestothemodelduringthecourseoftheproject.Theneedforformalproceduresisemphasizedin ordertocreatetrustworthymodels.Thisincludescross-checksonsimulation resultsbymeansofmathematicalanalysistoseethatthecomputermodelhasbeen implementedcorrectly.
Whenengineersusecomputermodelstoassistthemwithmakingcriticaldesigndecisionstheymustrememberthatthesolutionsobtainedwiththecomputeraregreatly dependentontheequationsthatwerecreatedtorepresentthephysicalhardware. Approximationsintheseequationsresultinapproximatesolutions.Theequationsused inthisbookmaybesufficientforanintroductiontothetopic,andindeedmanyhave beenusedforpreliminaryinvestigationsoftheproblemsthatwillbediscussed.However,beforereadersattemptseriousinvestigationsofthistype,itisrecommendedthat theysatisfythemselvesabouttheformoftheequationsthattheychoosetouse. Themomentoftrutharriveswhenthehardwareistested.Afterthis,thecomputermodelcanstillserveasthemeanswherebywecanquicklyandefficiently predictthebehaviorofthehardwareunderdifferentoperatingconditions.
1.3Mathematicalmaterial
Theadvanceofscienceledtothecreationofnewmathematicalmethodsthat describethenewtheoreticalconcepts.Thus,Newton’slawsofmotionledtothe creationofvectoranalysis,whileMaxwell’sequationsrequiredtheconceptofa
Bibliography 5
vectorfield.Suchmathematicalanalysisformsanintegralpartofthemodeling process,bothinthedefinitionofthemodelsandincheckingtheresults.Itwas thuspreferabletoincludeselectedmathematicalmaterialinseparateappendices thatcanbestudiedseparatelyorconsultedwhenreferredtointhechapters.
AppendixA describesfrequencyresponsetechniquesthatareusedinengineering,suchasthedesignoffeedbackcontrollers.ItshowshowMATLABandScilab candeterminelinearstateequationsandtransferfunctionsthatapproximatea givencomputermodel.
AppendixB describestheuseofvectorstocreatekineticmodelsofpointmasses andrigidbodies.
AppendixC describestheapplicationofvectorfieldstosolvediffusionand waveequations.
AppendixD discussesthemathematicalmodelingandanalysisofrandom events.
1.4Someremarks
MathematicalmodelingbeganwhenGalileoandNewtonmarriedthesciencesof astronomyandmathematics.Manyprofessionshavesinceusedcalculustoanalyzesystemsofeverydescription.Asthecalculationsbecamemorecomplex,scientistsbegantocreatecomputermodels.Thisbeganwiththecreationofanalog computersandthedevelopmentofsophisticatedsimulationtechniques.Some ofthebooksthatwerewrittenonthesubjectarelistedbelowandarestillavaluablesourceofinformationtoanyonewhowishestocreatecomputermodels. Oncethemodelhasbeenmathematicallydefined,itisnowpossibletouseadigital simulationplatformthatgreatlysimplifiesitsprogrammingonthecomputer.We canthenexperimentwiththemodelandobtainanswerswithastonishingrapidity. Thiscreatesariskthatwesometimesforgettotakesometimeofftoconsider wherewearegoing.TheIBMCorporationusedtohandoutpostersthatcontinue togivegoodadvice “THINK.” Thescientistsofyesteryearcanstillserveasarole modelinthisregard.
Thisbookaimstoshowhowcreativethinking,mathematicalanalysis,andcomputermodelscanbeusedtogethertoachieveasynergythatmaynototherwisebe apparenttothereader.Italsotakestruewisdomtodecidehowrealisticamodel mustbeandwhatisenoughtosatisfyourneeds.
Bibliography
Abbasov,I.B.(2019). ComputerModelingintheAerospaceIndustry.NewYork:Wiley. Hamming,R.W.(1962). NumericalMethodsforScientistsandEngineers.NewYork: McGraw-Hill.
Karplus,W.J.(1958). AnalogSimulation.NewYork:McGrawHill.
Korn,G.A.andKorn,T.M.(1956). ElectronicAnalogComputers.NewYork: McGrawHill.
Paynter,H.M.(1960). APalimpsestontheElectronicAnalogArt,Dedham.MA: PhilbrickResearches.
Raczynski,S.(2014). ModelingandSimulation.NewYork:Wiley.
Rogers,A.E.andConnoly,T.W.(1960). AnalogComputationinEngineeringDesign NewYork:McGrawHill.
Rubin,O.(2016). ControlEngineeringinDevelopmentProjects,Dedham.MA: ArtechHouse.
ShearerJ.L.,Murphy,A.T.andRichardson,H.H., IntroductiontoSystemDynamics, Reading,MA:Addison-Wesley,1967
Soroka,W.W.(1954). AnalogMethodsinComputationandSimulation.NewYork: McGrawHill.
Tomovic,R.andKarplus,W.J.(1962). HighSpeedAnalogComputers.NewYork:Wiley.
FromComputerHardwaretoSoftware
Thischapterspendslessthan5%ofitstimeonthecomputerandover95%ofits timeonthesoftware.
“Forthemachineisnotathinkingbeing,butsimplyanautomaton whichactsaccordingtothelawsimposeduponit.”
Ada,CountessofLovelace,1843
(Source: InthePublicDomain,RightsHolderAugustaAdaKing)
Wewillcodecomputermodelsinaprogramminglanguagethatbearsnoresemblancetothecodethatcontrolsthecomputingcircuits.
2.1Introduction
ThemissionstatementinChapter1describedalearningcurvethatprogresses frombasicprogrammingtothemostchallengingtechniquesofcomputermodeling.Thischapterbeginsbygivingashortintroductiontothedigitalcomputer.It willthengoontodescribeaprogramminglanguagethatwilltypicallybeusedin laterchapters.Itwillalsoshowsomefundamentaltechniqueswherebythislanguagecanbeusedtoperformrelativelycomplextasks.Laterchapterswillconsider modelsofcontinuousmotionbymeansofdifferentialequations;thuswerequire methodswherebyadigitalcomputer,whichisadiscretedevice,canemulatecontinuousbehavior.Section2.7presentstechniqueswherebythiscanbeachieved.
2.2Computingmachines
Ourword “calculate” comesfromtheRoman calculus (apebble).Aprimitiveabacususedpebblesthatwerelaidinfurrowsofsand.Overmanycenturiesmachines weredevelopedtospeedupsuchcalculations.LeonardodaVinci(1452–1519)left
ComputerModelsofProcessDynamics:FromNewtontoEnergyFields,FirstEdition. OlisRubin.
©2023TheInstituteofElectricalandElectronicsEngineers,Inc. Published2023byJohnWiley&Sons,Inc.
sketchesofthemechanismsthatareusedinamechanicaladdingmachine.Pascal (1623–1662)inventedacalculatorthatwasusedbyhistax-collectorfather.Then Babage(1791–1871)attemptedtocreateamachinethathadthecapabilityofthe moderncomputer(Swade,1991).
OneeveningIwassittingintheroomsoftheAnalyticalSocietyatCambridge…, withatableoflogarithmslyingopenbeforeme.Anothermember…calledout. ‘Well,Babage,whatareyoudreamingabout?’ towhichIreplied, ‘Iamthinking thatallthesetablesmightbecalculatedbymachinery.”
CharlesBabage
Babage’sfirstmachine,the “DifferenceEngine,” hadanabilitytorepeatcalculationsthathadneverbeenachievedbefore.Heabandonedthistoembarkonamuch moreambitiousproject,the “AnalyticalEngine.” Thismachineembodiedmanyof thefeaturesofmodernelectroniccomputers.Itwasprogrammableusingpunched cards,socomplexactionscouldbeachievedbymeansofagroupofmoreelementary instructions.Ithada “store” wherenumbersandintermediateresultswereheldand aseparate “mill” wherethearithmeticprocessingwasperformed.Themachinecould implementcomputingloopsandwascapableofperformingconditionalbranching:
Aformof IF THEN ELSE
Themachinewouldhavebeenthesizeofasmalllocomotive – 15feethigh,6feet across,and,inoneversion,20feetlong.Haditbeenbuilt, “calculatingbysteam” wouldhavebeenapropheticwishcometrue.
In1944AikenbuiltanelectromechanicalversionofBabage’ sAnalytical Engine(Trask,1971).Bernstein(1963)describestheoperationofthismachine: “ Onecouldgoinandlistentothegentleclickingofitsrelays,whichsounded likearoomfullofladiesknitting. ” Thiswasfollowedin1945bytheENIAC,an electronicdigitalcomputerthatcontained18000thermionicvalvesthat consumed150kWofelectricity(Trask,1971).Theinventionoftransistors andintegratedcircuitsthenallowedthecr eationoflow-cost,high-performance microprocessors.
2.2.1Thesoftwareinterface
Digitalcomputersareabletoperformcomplexoperationsbyexecutingmanysimpleactionsindiscretesteps.Thefirstcomputerswereprogrammedbywritingeach stepseparatelyinbinarycode.Suchasetofinstructions,knownasaprogram,can thenbeloadedintothecomputermemorybank.Thecomputerthenperformsthe particularoperationbyreadingtheinstructionsfrommemoryandexecutingthem step-by-step.Specialprogramswerethendevelopedandinstalledinthecomputer thatallowustowriteourinstructionsinasimplerlanguage.Suchaninstalled 8
programthentranslatesourstatementsintobinaryinstructionsthatareexecuted bythecomputer.Todaytherecanbeseverallayersofsoftwarethatactasaninterfacebetweentheuserandtheactualcomputerhardware.
Withtheadventofpersonalcomputers(PCs)inthe1980sthestagewassetfor thedevelopmentofthedigitalsimulationplatformsoftoday.ThefirstPCswere slowandhadlittlememory,butJohnLittleanticipatedthattheywouldeventually becapableofeffectivetechnicalcomputingandinitiatedthedevelopmentofthe productthatisknownasMATLAB® (Moler,2006).Thiscanexecuteprogramfiles toperformmanyscientificandengineeringtasks.Numericalresultscanthenbe displayedorplottedinhigh-resolutiongraphics.
2.3Computerprogramming
Scientificcomputationscanbedonethroughunderlyingsoftwarethatallowsusto writeourinstructionsinalanguagethatresemblestheequationsthatarefamiliar tomathematicians.Atypicalinstructiontoperformanarithmeticcalculation takestheformofastatementthathasthefollowingformat:
variable=expression;
Mathematicianswriteequationsinthiswaytodefinevariablesasalgebraicfunctionsofothervariables.Theaboveinstructionwillcausethecomputertoperform acalculationthatisdefinedbythe expression ontheright-handsideoftheequal (=)sign,andsavetheresultasthe variable thatisdefinedontheleft-handside. Thisissavedasabinarynumberinitsmemory.Itisnecessarytoidentifythelocation(address)ofthis variable inthememorybank,sothatitcanberetrievedfor lateruse.Theunderlyingsoftwareplatformthatsupportsthescientificlanguage providesauserinterfacewherenumbersaredisplayedasdecimals,whilethe addressofthe variable isdisplayedasanamethatiswritteninalphanumeric characters.
Severalscientificlanguageshavebeendeveloped,eachofwhichhasaslightly differentalgebraicsyntax.
Theprogramlistingsgiveninthisbookareextractedfromprogramsthatwere createdandrunoneithertheScilabortheMATLABsoftwareplatform.Programs thataresavedinafilewiththeextension.sce canberunbyScilab,whilefileswith theextension .m canberunbyMATLAB.Theindividualinstructionsintheseprogramscanalsobetypedandruninthecommandwindowsoftherespectiveplatforms.Thenextsections(2.3.1–2.3.6)giveashortintroductiontothebasicsyntax thatisused.Readerswhowriteprogramsusingtheseplatformscanconsulttheir built-inHelpfacilitiesforfurtherinformation.UserGuidesarealsoavailable, whichgivemorebasictraining.
2.3.1Algebraicexpressions
MATLABandScilabperformarithmeticalcalculationsonnumericalobjects.The instructiontoperformaparticularcalculationiscreatedbytypingastatementof theformthatwasshownintheprevioussection.Forexample,wecoulddefinethe radiusofacirclebythefollowingstatement:
r=1.2;
Thiswouldinstructthecomputertosavethenumericalvalueoftheradiusinits memorybank.Ifwenowtypetheletter r inthecommandwindowwewouldsee thefollowing:
Thisquantityisnowavailableforfurtheruse.IfweareusingScilabwecould calculatetheareawithinthiscirclebythefollowingstatement:
A=%pi*(r^2);
Scilabhasapredefinedvariable %pi thatisequaltotheratioofacircle’scircumferencetoitsdiameter,whileMATLABusesthesymbol pi toidentifythisnumber.Thebracketsdefinetheorderofexecution.Theabovestatementwillthus causethesquareoftheradiustobecalculatedbeforeitismultipliedby %pi. Nowsupposethatwehavedefinedthelengthofacylinderbythesymbol L.We couldthencalculateitsvolumebythefollowingstatement:
V=(%pi*(r^2))*L;
Otherarithmeticoperationsaresimilarlycoded.Theirdefaultorderofexecution isasfollows:
^ exponentiation + addition - subtraction
* multiplication / division
ScilabandMATLABallowustocreatevariables “onthefly” astheyaredefinedby statementswithinaprogram.Theirnumericalvaluescanthenbechangedbysubsequentstatements.Ifastatementreferstoacalculationthatinvolvesavariable y that hasnotbeenpreviouslycreated,theprogramwillendanddisplayanerrormessage: Undefinedvariable:y
2.3Computerprogramming
MATLABandScilabaredesignedtoperformarithmeticalcalculationson numericalvectorsandmatrices,wherescalarsareregardedtobe1-by-1matrices. Supposethatwehavecreatedthefollowingscalars:
a11=1; a12=2; a21=3; a22=4;
Wecouldthencreatethefollowingrowvectors:
R1=[a11,a12]; R2=[a21,a22];
Ifwenowtypethename R1 inthecommandwindowwewouldseethe following:
R1= 1.2.
Theserowvectorscanthenbecombinedtoformamatrix:
M=[R1;R2];
Ifwenowtypethename M inthecommandwindow,wewouldseethe following:
M= 1. 2. 3. 4.
Wecanalsoaddresstheindividualelementsinamatrix,inordertousetheir valuesinfurthercalculations.Forexample,ifwetypethe M(1,2) inthecommandwindowwewouldseethefollowing:
ans= 2.
Similarly,ifwetypethe M(2,1) inthecommandwindowwewouldseethe following:
ans= 3.
Alternatively,wecouldhavecreatedthefollowingcolumnvectors:
C1=[a11;a21]; C2=[a12;a22];
Ifwenowtypethename C1 inthecommandwindowwewouldseethefollowing: C1= 1. 3.
Thesecolumnvectorscanthenbecombinedtoformthesamematrix: M=[C1,C2];
Wecanalsoaddresstherowandcolumnvectorsinamatrix.Forexample,ifwe type M(2,:) inthecommandwindowwewouldseethefollowing:
ans= 3. 4. whileifwetype M(:,2) inthecommandwindowwewouldseethefollowing:
ans= 2. 4.
Amatrix N canbeaddedtoorsubtractedfromasecondmatrix(M)providedthat theyhavethesamedimensions.Considerthefollowingstatement:
A=M+N;
Theindividualelementsofthematricesareaddedtogether,sothatA(i,j)= M(i,j)+N(i,j).
Twomatrices M and N canbemultipliedusingthefollowingstatement,provided thatthenumberofcolumnsof M equalsthenumberofrowsof N:
A=M*N; Forexample,ifMisarowvector[m1,m2]andNisacolumnvector[n1;n2],the abovestatementproducesthescalarproduct:
A=m1n1 +m2n2
IfMisasquarematrixtheexpression M^2 isequivalentto M*M while M^3 is equivalentto M*M*M.
Similarly, M^0.5*M^0.5 isequalto M and M^1.5 isequalto M*M^0.5.
Twomatricescanbemultipliedelement-by-elementprovidedthattheyhavethe samedimensions.Thefollowingstatementgivessuchamatrixthathasthesame dimensionsas M and N:
A=M.*N;
2.3Computerprogramming
Theexpression M./N giveselement-by-elementdivision,whiletheexpression M.^2 isequivalentto M.*M
TheHelpfacilitiesandUserGuidesgivebetterinformationonsuchoperations; forexample,howtodivideonematrixbyanother.
2.3.2Mathfunctions
MATLABandScilabhavebuilt-infunctions,suchas:
sqrt squareroot sin sine
cos cosine
tan tangent asin arcsine atan arctangent atan2 fourquadrantarctangent
exp exponentialtobasee log naturallogarithm log10 logtobase10
factorial(4)=1*2*3*4
M’ matrixtranspose(rowvectortocolumnvectorandvice versa)
If M isamatrix,theexpression sqrt(M)willapplythesquarerootoperation element-by-element.Otherfunctionsoperateinthesameway.Wecanalsonest functions,asshownbythefollowingexample: s=sqrt(exp(A))
Thisbringsustocomplexnumbers.Ifwetypetheexpression sqrt(-1) inthe Scilabcommandwindowwewouldseethefollowingsymbolfortheunitaryimaginarynumber: ans= i
Scilabhaspredefinedthisquantity,sothestatement c=3+(4.5*%i) creates acomplexvariable. Ifwethentypethesymbol c inthecommandwindow,wewouldseethe following:
c= 3.+4.5i
Wecansimilarlycreateacomplexmatrixsuchas M+(N*%i). Unlike sqrt(M), theexpression M^0.5 canoperateonarealmatrixtogivea complexmatrix.
TheHelpfacilitiesandUserGuidesgivebetterinformationonavailable functions.
2.3.3Computationloops
Wearenowcomingtothosefeaturesthatdistinguishacomputerfroma calculator.
Considerthecalculationofthefollowingpolynomialtoproduceavariable y asa functionofagivenvariable(x):
y=a0+a(1)*x+a(2)*x^2+...+a(99)*x^99 wherethecoefficientsaredefinedastheelementsofavector:
[a(1),a(2),...,a(99)]
Wecanuseacalculatorasfollows,tocalculatetheindividualtermsandadd themsuccessivelytoarunningtotal:
y=a0
y=y+a(1)*x y=y+a(2)*x^2 /////////// y=y+a(99)*x^99
Onacomputer,wecanavoidthelaboriousprocessofseparatelyprogramming eachindividualstepbycreatingacomputingloop.MATLABandScilabhavestatementsthatallowustodothisasfollows:
y=a0; K=99; fork=1:K
y=y+a(k)*x^k; end;
Alltheoperationsthatappearbetweenthe for statementandthe end keywordwillbeexecuted99times.Inthisexamplethereisasingleoperation,which calculatesaterm a(k)*x^k andaddsittotherunningtotal(y).Thecomputing loopgoesaroundfrom for to end andbackto for.The for loopusesacounter,thevariable k,tokeeptrackofthenumberoftimesthattheoperationhas beeniterated.Thisisatruevariablethatcanbeusedwithinthecalculations.In thisexampleithasbeenusedtoaddresstheelements a(k) ofthevector,and alsotodeterminethepowertowhichthevariable x mustberaised.The
2.3Computerprogramming
expression 1:K referstoanactualvector.Thestatement V=1:K; wouldproducearowvectoroftheform:
Ratherthancalculatingapolynomialwithagivennumberofterms,wemay wishtocomputethevariable y toanaccuracyof1%.MATLABandScilaballow ustodothisasfollows:
y=a0; k=1; z=a0; whilez<y
y=y+a(k)*x^k; k=k+1; z=100*a(k)*x^k; end;
Inthiscasetherearethreeoperationsbetweenthe while statementandthe end keyword.Beforeitbeginsthefirstiteration,thecomputingloopteststo seewhethertheexpression z<y istrue.Thesymbol < isarelationaloperator.With MATLABthestatement u=z<y wouldproduceavariable u thatissettooneif x is lessthan y,andtozeroif x isnotlessthan y.Thelaststatementintheloopcomputesthenexttermofthepolynomialandthengoesbacktothetest(z<y).Ifthe nexttermislessthan1%oftherunningtotal,theprogramexitsfromtheloop. WithScilabthestatement u=z<y producesaBooleanvariablethatis%T(fortrue) or%F(forfalse).
Computingloopscanalsobenested.Thuswecouldusethefollowingprogramto calculate y for M valuesof x thatarestoredinavector(X):
Y=[]; form=1:M x=X(m); y=a0; fork=1:K
y=y+a(k)*x^k; end; Y=[Y,y]; end
The M valuesof y havebeenstoredinarowvector(Y).
2.3.4Decisionmaking
The while loopconsideredinthelastsectionusedtheresultofanexpression (z<y)todecidewhethertocontinueiteratingorexitingfromtheloop.Thisexpressionusestherelationaloperator < totestwhether x islessthan y.MATLABand Scilabhaverelationaloperatorsthatincludethefollowing:
lessthan
greaterthan
equalto
notequalto
Thebooleanvariables%T(fortrue)and%F(forfalse)usedbyScilabcanbecombinedtotestwhetherseveralconditionsaresatisfied.MATLABcansimilarlycombinebinaryvariables.Thisisachievedbymeansofthelogicaloperators: & logicalAND | logicalOR ~ logicalNOT
Manyprogramsmustdecidebetweenseveralcoursesofactionthatcouldbe takentoachieveagivenobjective.Forexample,considerthedescriptionofa motorthatmovesthroughadistance(x)todriveamachinethroughmechanical links.Therecouldbeplay P inthelinksbefore x causesanymotion(y)ofthe machine.Supposethattheequivalentgearratioofthelinkscanthenbeexpressed bythefollowingrelationship:
y=N*(x-P)
Wemaythenhaveanendstopthatprevents y frommovingbeyondaposition E Supposethatthelinkscanbendelastically,allowingthemotortomovebeyondthe point (E/N)+P.Wemaydecidetouseagrossapproximationinordertomodel thisbehaviorbyamathematicalfunction y = f (x)thathasthefollowingproperties:
Y=0:whenxislessthanP
Y=N*(x-P):whenxliesbetweenPand(E/N)+P
Y=E:whenxexceeds(E/N)+P
Wecanrealizethisfunctionbymeansofthefollowingprogram:
ifx<P
y=0; elseifx<(E/N)+P
y=N*(x-P); elsey=E; end
2.4Statetransitionmachines
Weseethattheregionwhere y movesfromzeroto E satisfiestwoconditionsthat couldbecombinedintotheexpression (x>=P)&(x<(E/N)+P)
Morecomplexprogramscanusevariouscombinationsofloopsand if statements.
2.3.5Graphics
MATLABandScilabcancreatevariousplotsofnumericalresults.Thebulkofthe examplesinthisbookusethestatement plot(X,Y) toplotagraphofavector Y versusthevector X.Theelements X(i) canrepresentthevaluesofanindependentvariable,whiletheelements Y(i) canrepresentafunctionof X(i).Frequencyresponsescanbeplottedagainstalogarithmicfrequencyaxis. Section6.3.4showshowthisisdoneinScilab,whileSection10.4.1showssimilar MATLABinstructions.Athree-dimensionalplotisshowninFigure7.14.Thiswas createdbytheScilabstatement plot3d(X,Y,Z).TheMATLABandScilabHelp facilitiesandUserGuidesgivebetterinformationonavailablegraphicsfeatures.
2.3.6Userdefinedfunctions
Wehaveseenthepowerthataniterativeloophasgivenacomputer.Theconcept ofafunctionextendsthispowerbyallowingustocallupacomputingprocedure at will,atdifferentpointsintheprogram.AppendixA.3givesanexampleofthecoding ofafunctioninScilab.TheMATLABHelpfacilityandUserGuidegiveinformationonthecodingofanequivalentfunction.
2.4Statetransitionmachines
Adigitalcomputerisastatetransitionmachine.Ateveryclockpulsethereisa changeinthepatternofbits(0or1)thatisstoredinitsmemorybankanditselectronicregisters.Theexecutionofalineofcodetypicallyinvolvesoneormoreofthe followingactions,eachofwhichchangesthestateofthemachine:
loadaprogramstatementintothecontrolunit loadavariableintotheprocessor executethestatementtocomputethevalueofavariable savethevariableinmemory
Wewillnowdescribeadigitalmachinewhosestateisdeterminedbythepattern ofbitsthatisstoredinasingleshiftregister.Everyclockpulsewillcauseachange initsstate,whichisdeterminedbyhard-wiredinterconnections.Themachine resemblesanelementarycomputer,wheretheprogramconsistsoftheseinterconnections.Wethushaveasinglestatementthatisendlesslyrepeated.Thedevice canalsobeimplementedonamicrocontrollerasanalgorithmthatisrepeated
wheneveritreceivesaninterruptsignalfromtheclock.Thealgorithmcanbe testedbyaprogramthatusesa for looptosimulatetherepetitionsthatoccur intheactualhardware.WewilluseScilabforrunningsuchatest.
2.4.1Abinarysignalgenerator
Consideradevicethatusesvariousdigitalelementstoproduceasequenceof binarypulses.Binarydataisstoredinbistableflip-flops,eachofwhichstoresa singlebitinatransistorthatisswitchedONorOFF.Theflip-flopsareinterconnectedinastringtoformashiftregister.Whenthemachinereceivesaclockpulse, thepatternofbitsintheregisterismovedbyonepositiondowntheline.Logic operationsareperformedbyAND,OR,andNOTgates.
Wecanalsoimplementthedeviceasanalgorithmonamicrocontroller.The stateoftheshiftregisterisgivenbyavector(x)whoseelementsareeitherones orzerosandaninputsignal z=1 or 0.Wewillbeginwithastatevector(x)that hasthreeelements.Wheneverthemicrocontrollerreceivesaninterruptsignal fromtheclockthepatternofbitswillbeshifted: fromx(2)tox(3) fromx(1)tox(2) fromztox(1)
WecanimplementthealgorithmbythefollowingScilabprogram: fork=1:4
x(3)=x(2); x(2)=x(1); x(1)=z(k); X=[X;x]; end
Supposethattheinitialstateis x=[010] and z=[1111]
Thelaststatementintheloopgatherstherowvectors(x)thatshowtheevolutionofthestateintoamatrix(X)thatcanthenbedisplayedas: X(:,1)X(:,2)X(:,3) 0.1.0.
Havingverifiedtheoperationoftheshiftregister,wewishtoimplementabinary feedbackloopbyusinganexclusive-orgatetocombine x(3) and x(2) andfeedingitsoutput(z)backto x(1).Thisimpliesthat z willbe1providedthatone inputis1andtheotheris0.Theexpression x(3)~=x(2) canbeusedtorealize