andrea mignone physics department, university of torino aa...
TRANSCRIPT
NumericalAlgorithmsforPhysics
AndreaMignonePhysicsDepartment,UniversityofTorino
AA2019-2020
CoursePurpose• Physicsisoftendescribedbyequationsthatcannotbesolvedanalyticallyorcannot
beeasilyexpressedinclosedforms.• Popularexamplesare
– Pendolum:
– Parabolicmotionwithairdrag:
– Atomswithmanyelectrons,time-dependentfluiddynamics,N-bodyproblems,etc…
• Inthiscourse,youwilllearnhowtosolvescientificproblemsbywriting(from
scratch)acomputerprogram.
• WewilluseC++asourprimarylanguage,althoughonlyinitsbasicform(noobject-orientedprogramming):
– Understandhowacomputerprogram(code)works;– Bewareofthelimitations;– Interpret,analyzeandvisualizeresults.
CourseObjectives&Requisites• Althoughfarfrombeingcomplete,thecourseaimsatteachingbasicnumerical
methodologyandwillcoverthefollowingtopics:
– Definiteandindefiniteintegrals(alsoknownasnumericalquadrature);– Randomnumbersand(aprimerto)MonteCarlomethods;– Rootfindermethodsfornonlinearequations;– OrdinaryDifferentialEquations(ODE),initial&boundaryvalueproblems;– Numericaldifferentiation;– Linearsystemsofequations;– Ellipticpartialdifferentialequations(PDE);
• Pre-requisites:
– Mechanics,electromagnetism,quantumphysics;– AcquaintancewithC/C++programminglanguage;– Someknow-howofLinuxsystem.
CourseEvaluation&OtherInfo• Attendancetoclassesisstronglyrequired.
• There’refewexceptions:scheduleincompatibility(reporttome),overlappingwithothercourses.
• Lectures&onlinematerialathttp://personalpages.to.infn.it/~mignone/Numerical_Algorithms/• Finalgradewillbeestablishedon:i)learningabilityshownduringlectures,homework
assignementandii)(optionally)asupplementaryprojectofyourchoicetobedeliverednolaterthanoneyearfromthebeginningofthecourse.
• Youarefreetoworkonyourlaptop,ifyouknowwhatyou’redoing.
SuggestedTextbooksReferencetextbooksonC++:• “C++PrimerPlus(Developer’sLibrary)”(6thedition)byS.Prata• “PracticalC++Programming”(2ndedition)byS.OuallineReferencetextbooksonnumericalmethods:• “NumericalRecipes”…• “ASurveyofComputationalPhysics”Landau• “ComputationalPhysics”
UnixShell• AUnixshellisacommand-lineinterpreter(CLI)thatprovidesaninterfacetotheUNIX
system.
• Itgathersinputfromyouandexecutesprogramsbasedonthatinput.Whenaprogramfinishesexecuting,itdisplaysthatprogram'soutput.
• Ashellisdefinedbyitsenvironmentinwhichwecanrunourcommands,programs,andshellscripts.Therearedifferentflavorsofshellswiththeirownsetofrecognizedcommandsandfunctions.
• Mostlikely,thebashshellwillbethedefaultonyoursystem(otherpossibilitiesarecsh,tcsh,zsh,etc…).
Handlingdirectories:ls,pwd,cd,mkdir• Thecommandlsisusedtolistthecontentofadirectory.Additionalcommandline
options(suchas-l,-lt,-lh)canbegiven,seethemanpage(manls)
• Thepwdcommandprintsthecurrentworkingdirectory($HOME);
• Thecdcommandisusedtochangedirectory:
• Themkdircommandisusedtocreateanewdirectory:
>ls-l-rw-r--r--1mignonestaff298Apr1616:22conta.cpp-rwxrwxrwx1mignonestaff1288Apr1219:27factorial.cpp-rwxrwxrwx1mignonestaff979Apr1218:59guess.cpp-rwxrwxrwx1mignonestaff745Apr1616:45operations.cpp-rwxrwxrwx1mignonestaff574Apr1615:35welcome.cpp
>cdMy_Folder#changedirectorytoMy_Folder>cd../#goonelevelup
>mkdirNew_Folder#createdirectoryNew_Folder
Handlingfiles:cp,mv,rm• cpcanbeusedtocopyfilesanddirectoriesfromonelocationtoanother,e.g.
• mvcanbeusedtorenameormoveafilefromonelocationtoanother,e.g.
• rmisusedtodeletefiles:
Attention:removecommandcannotbeundone!
>cpsourcedest#copy‘source’to‘dest’>cpfile../#copy‘file’onelevelup>cpfile1file2file3My_Dir/#copythreefilestothedirectory‘My_Dir’
>mvsourcedest#rename‘source’to‘dest’>mv...#copythreefilestothedirectory‘My_Dir’
>rmfile1#delete‘file1’>rm./*#removeallfilesinthecurrentdirecoty
Usingwildcards• Wildcardsareusedtoworkwithmultiplefiles:
– ?(questionmark):thisrepresentsanysinglecharacter,example
– *(asterisk):thisrepresentsanynumberofcharacters(includingzero).Example:
>lsfo?.c#maylistfo1.cfo2.cfo3.c,foo.c,etc…
>lsfo*.c#maylistfo12.cfool.cfokker.c,etc…
UsefulTips&Tricks• Linuxcommandarecase-sensitive.
• Findingpreviouscommand:pressingtheUpkeyboardkeywillcyclethroughthelastLinuxcommandswesuccessfullyused,inorder.Nofailedcommandswillshowhere.
• UseTabtoautocomplete:the<Tab>buttononthekeyboardautomaticallyfillsinpartiallytypedcommands(orfilesnames).Itsavehugetime.
Example:– Ifwewanttodeleteafilenamed"whydidIgivethisfilesuchalongname",wejustneed
totype"rmw"andpressingTabwillautomaticallycompletetherestofthefilename.Note:Iftherearemorethanfilesthatbeginwiththesameletters,e.g."whydidIgivethisfilesuchalongname"and"whydidIeatsomuch",pressingTabon"rmw"willautocompletethecommon"whydidI".
CustomizingBashEnvironment• Bashenvironmentcanbecustomizedbyediting‘.bashrc’fileinyour$HOME
directory(onMacOS,thismaybefoundunder‘.profile’)
• Forinstance,
source$HOME/Lib/Scripts/utility.shexportPS1="\[\e[32;1m\][\u@\h]\w\[\e[0m\]\n>”exportPATH=<newpathshere>:$PATHaliasrm='rm-i'aliascp='cp-i'aliasmv='mv-i'
Howwewillwork:EditorDuringthiscourse,wewillusetheterminalforcompilationandexecution,butcodingwillbedoneinastandardtexteditor.Here’reafewchoices:• gedit(FrontendGUI)
• geany(FrontendGUI)
• nedit(FrontendGUI)
• vi/vim/nano(terminale)
• emacs
• komodoedit(GUI)
Your1stprogram:HelloWorld!• Useyoureditortoopenanewfile‘welcome.cpp’andtype
• Savefilesandcompilewith
• Thiswillcompile‘welcome.cpp’andproducetheexecutable‘welcome’.• Runtheprogrambytyping,attheterminal,
#include<iostream>//Preprocessordirectiveintmain()//FunctionHeader{usingnamespacestd;//Makedefinitionsvisiblecout<<std::endl;cout<<"-------------------------------------------+"<<endl;cout<<"+Helloworld!+"<<endl;cout<<"++"<<endl;cout<<"+WelcometotheNumericalAlgorithmClass+"<<endl;cout<<"+------------------------------------------+"<<endl;return0;}
>g++welcome.cpp–owelcome
>./welcome
ProgramStructure• C++programsareconstructedfrombuildingblockscalled
functions.
• Organizeaprogramintomajortasksandthendesignseparatefunctionstohandlethosetasks.• Thepreviousprogramconsistsofasinglefunctionnamed
main()withthefollowingelements:
#include...Func1(){statements}Func2(){statements}main(){statements}
cv
o Comments,indicatedbythe//prefixo Apreprocessor#includedirectiveo Afunctionheader:intmain()o Ausingnamespacedirectiveo Afunctionbodydelimitedby{and}o StatementsthatusestheC++coutfacilitytodisplayamessageo Areturnstatementtoterminatethemain()function
Themain()functionintmain(){statementsreturn0;}
• The main() function has the following fundamental structure:
• These lines state that there is a function called main() and describe how the function behaves.: together they constitute a function definition.
• In C++ each complete instruction is called a statement.
• Statement must terminate with a semicolon,
• It consists of – the function header intmain(): a
capsule summary of the function’s interface with the rest of the program,
– the function body: the portion enclosed in braces ({ and }), which represents instructions to the computer about what the function should do.
TheC++PreprocessorandtheiostreamFile• C++(likeC)usesapreprocessor:aprogramthatprocessesasourcefilebeforethe
maincompilationtakesplace.
• Preprocessordirectivesbeginwith#:
• The#includedirectivecausesthepreprocessortoaddthecontentsoftheiostreamfiletoyourprogramatcompilationtime:inpracticethecontentoftheiostreamfilewillreplacethe#include<iostream>line.
• Thisdirectivecauses,atypicalpreprocessoractionwhichaddsorreplacestextinthe
sourcecodebeforeit’scompiled.
• Thecontentoftheiostreamisaddedforcommunicationbetweentheprogramandtheoutsideworld.TheI/Oiniostreamreferstoinput-informationbroughtintotheprogram-andtooutput-informationsentoutfromtheprogram.
• C++’I/Oschemeinvolvesseveraldefinitionsfoundintheiostreamfile.
#include<iostream>//aPREPROCESSORdirective
PracticeSession#1• count.cpp:writeaprogramthatprintstheintegersnumbersfrom1to10,usingfor
andwhileloops.
• Modifythepreviouscodetoprintonlyoddnumbers.
• operations.cpp:giventwofloatnumbersandtwointegernumbers,performsimplearithmeticoperations(+,-,*,/)àwatchoutintegerdivision!
Functions• Considerasimpleprogramthatcomputesthesumoftwodoubleprecision
numbersandwriteaseparatefunctiontoperformthesum.• Anexampleisgivenhere:
#include<iostream>#include<cmath>doubleSum(double,double);intmain(){usingnamespacestd;doublea,b,c;a=1.5;b=3.7;c=Sum(a,b);return0;}doubleSum(doublex,doubley){returnx+y;}
Functiondeclaration(orprototype):doesforfunctionswhatavariabledeclarationdoesforvariables:ittellswhattypesareinvolved.
Functioncanbecalledfromanywherenow
TheFunctiondefinitionimplementstheactualbodyofthefunction.
PassingArgumentstoFunctions• Argumentstofunctioncanbepassedbyvalueorbyreference.• Byvalue:argumentstothefunctionarecopiedintothevariablesrepresentedbythe
functionparameters.Forexample,take:
• Byreference:whatispassedisnolongeracopybutthevariableitself:anymodificationtotheargumentsisreflectedinthevariablespassedasargumentsinthecall:
c=Sum(a,b);doubleSum(doublex,doubley){...}
Inthiscase,xandyarecopiesofthevariablesaandb:anymodificationofthesevariableswithinthefunctionhasnoeffectontheoriginalvalue.
AddOne(a);voidAddOne(double&x){x=x+1.0;}
Inthiscase,a(=x)ismodifiedandafterthecallithasbeenincrementedbyone.
PracticeSession#2• sum.cpp:computethesumoftwointegers(orfloats)
• add_one.cpp:addonetoanumber.
• quotient.cpp:writeafunctionthatcomputesthequotientandremainderofthedivisionoftwointegers,aandb.Example– 10/7=1remainder3– 13/6=2remainder1,etc..
• arrays.cpp:computetheaverage,varianceandstandarddeviationofanarray.Youcanusethedrand48()functiontofillthearraywithrandomnumbers.
TypicalErrors,goodandbadprogramminghabits
Indentationinti;for(i=0;i<10;i++){if(i==5){cout<<“Iamnumberfive”<<endl;}}
NO!!
inti;for(i=0;i<10;i++){if(i==5){cout<<“Iamnumberfive”<<endl;}}
YES!!
Indentationclarifiesthelinkbetweencontrolflowconstructssuchasconditionsorloops,andcodecontainedwithinandoutsideofthem.Thecodewillbei)easytoread,ii)easytounderstand,iii)easytomodify,iv)easytomaintain.
TypeCasting(1/2=0)inti,n;doubleq;for(i=0;i<n;i++){q=i/n;q=(double)(i/n);}
NO!!
inti,n;doubleq;for(i=0;i<n;i++){q=(double)i/(double)n;}
YES!!
Mixinglower-andupper-caseintI;doublea[i];Cin>>I;
NO!!
inti;cin>>i;doublea[i];
YES!!
The==signandthe=signfor(i=0;i<10;i++){if(i=5)break;}
NO!!
for(i=0;i<10;i++){if(i==5)break;}
YES!!
FloatingPointarithmeticdoublex=0.0;while(1){x+=0.1;if(x==10.0)break;}cout<<"x=%f\n"<<x<<endl;return0;
NO!!
doublex=0.0;while(1){x+=0.1;if(fabs(x-10.0)<1.e-6)break;}cout<<"x=%f\n"<<x<<endl;return0;
YES!!
Roundingerrordoublex,dx;for(x=0.0;x<=xend;x+=dx){...}//Thiswillyield(xend=1.0,dx=0.1):////x=0.0,0.1,0.19999,0.200003
NO!!
inti;for(i=0;i<N;i++){x=x0+i*dx...}
YES!!
HomeworkAssignmentfactorial.cpp:writeacodethatcomputesthefactorialofanintegern.Implementthealgorithmusingtwodifferentstrategies:1. Usingastandardfor()loop(orarecursivefunction)andintegerarithmetic.Verify
itsimplementation.Whatisthemaximumnumberforwhichthefactorialcanbecomputed?
2. Addasecondfunctionthatemploysdoubleprecisionarithmetic;canyoutakethe
factorialoflargernumbers?Explainwhy.Pleaseprovideasinglesourcefileintheform“surname_factorial.cpp”(wheresurnameisyourlastname!)atthelinkprovidedonthecoursewebpage.