andrea mignone physics department, university of torino aa...

28
Numerical Algorithms for Physics Andrea Mignone Physics Department, University of Torino AA 2019-2020

Upload: others

Post on 29-Oct-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

NumericalAlgorithmsforPhysics

AndreaMignonePhysicsDepartment,UniversityofTorino

AA2019-2020

Page 2: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

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.

Page 3: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

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.

Page 4: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

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.

Page 5: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

SuggestedTextbooksReferencetextbooksonC++:•  “C++PrimerPlus(Developer’sLibrary)”(6thedition)byS.Prata•  “PracticalC++Programming”(2ndedition)byS.OuallineReferencetextbooksonnumericalmethods:•  “NumericalRecipes”…•  “ASurveyofComputationalPhysics”Landau•  “ComputationalPhysics”

Page 6: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

UnixShell•  AUnixshellisacommand-lineinterpreter(CLI)thatprovidesaninterfacetotheUNIX

system.

•  Itgathersinputfromyouandexecutesprogramsbasedonthatinput.Whenaprogramfinishesexecuting,itdisplaysthatprogram'soutput.

•  Ashellisdefinedbyitsenvironmentinwhichwecanrunourcommands,programs,andshellscripts.Therearedifferentflavorsofshellswiththeirownsetofrecognizedcommandsandfunctions.

•  Mostlikely,thebashshellwillbethedefaultonyoursystem(otherpossibilitiesarecsh,tcsh,zsh,etc…).

Page 7: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

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

Page 8: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

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

Page 9: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

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…

Page 10: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

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".

Page 11: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

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'

Page 12: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

Howwewillwork:EditorDuringthiscourse,wewillusetheterminalforcompilationandexecution,butcodingwillbedoneinastandardtexteditor.Here’reafewchoices:•  gedit(FrontendGUI)

•  geany(FrontendGUI)

•  nedit(FrontendGUI)

•  vi/vim/nano(terminale)

•  emacs

•  komodoedit(GUI)

Page 13: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

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

Page 14: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

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

Page 15: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

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.

Page 16: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

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

Page 17: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

PracticeSession#1•  count.cpp:writeaprogramthatprintstheintegersnumbersfrom1to10,usingfor

andwhileloops.

•  Modifythepreviouscodetoprintonlyoddnumbers.

•  operations.cpp:giventwofloatnumbersandtwointegernumbers,performsimplearithmeticoperations(+,-,*,/)àwatchoutintegerdivision!

Page 18: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

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.

Page 19: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

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.

Page 20: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

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.

Page 21: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

TypicalErrors,goodandbadprogramminghabits

Page 22: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

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.

Page 23: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

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!!

Page 24: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

Mixinglower-andupper-caseintI;doublea[i];Cin>>I;

NO!!

inti;cin>>i;doublea[i];

YES!!

Page 25: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

The==signandthe=signfor(i=0;i<10;i++){if(i=5)break;}

NO!!

for(i=0;i<10;i++){if(i==5)break;}

YES!!

Page 26: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

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!!

Page 27: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

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!!

Page 28: Andrea Mignone Physics Department, University of Torino AA …personalpages.to.infn.it/~mignone/Numerical_Algorithms/ch01... · -rwxrwxrwx 1 mignone staff 979 Apr 12 18:59 guess.cpp

HomeworkAssignmentfactorial.cpp:writeacodethatcomputesthefactorialofanintegern.Implementthealgorithmusingtwodifferentstrategies:1.  Usingastandardfor()loop(orarecursivefunction)andintegerarithmetic.Verify

itsimplementation.Whatisthemaximumnumberforwhichthefactorialcanbecomputed?

2.  Addasecondfunctionthatemploysdoubleprecisionarithmetic;canyoutakethe

factorialoflargernumbers?Explainwhy.Pleaseprovideasinglesourcefileintheform“surname_factorial.cpp”(wheresurnameisyourlastname!)atthelinkprovidedonthecoursewebpage.