id
int64
0
25.6k
text
stringlengths
0
4.59k
3,800
exercises cwrite function mystruct(textthat counts the number of certain structure in the string text the structure is defined as followed by or until double gg perform manual search for the structure too to control the computations by mystruct filenamecount_substrings py remarks you are supposed to solve the tasks using simple programming with loops and variables while aand bare quite straightforwardcquickly involves demanding logic howeverthere are powerful tools available in python that can solve the tasks efficiently in very compact codeatext count(letter)/float (len(text))btext count(letter* )clen(re findall(' [at]+?gg'text)that isthere is rich functionality for analysis of text in python and this is particularly useful in analysis of gene sequences open access this is distributed under the terms of the creative commons attributionnoncommercial international license (which permits any noncommercial useduplicationadaptationdistribution and reproduction in any medium or formatas long as you give appropriate credit to the original author(sand the sourcea link is provided to the creative commons license and any changes made are indicated the images or other third party material in this are included in the work' creative commons licenseunless indicated otherwise in the credit lineif such material is not included in the work' creative commons license and the respective action is not permitted by statutory regulationusers will need to obtain permission from the license holder to duplicateadapt or reproduce the material
3,801
computing integrals we now turn our attention to solving mathematical problems through computer programming there are many reasons to choose integration as our first application integration is well known already from high school mathematics most integrals are not tractable by pen and paperand computerized solution approach is both very much simpler and much more powerful you can essentially treat all integrals rb /dx in lines of computer code (!integration also demonstrates the difference between exact mathematics by pen and paper and numerical mathematics on computer the latter approaches the result of the former without any worries about rounding errors due to finite precision arithmetics in computers (in contrast to differentiationwhere such errors prevent us from getting result as accurate as we desire on the computerfinallyintegration is thought of as somewhat difficult mathematical concept to graspand programming integration should greatly help with the understanding of what integration is and how it works not only shall we understand how to use the computer to integratebut we shall also learn series of good habits to ensure your computer work is of the highest scientific quality in particularwe have strong focus on how to write python code that is free of programming mistakes calculating an integral is traditionally done by zb xdx /( where xd df dx (cthe author( lingeh langtangenprogramming for computations pythontexts in computational science and engineering doi --
3,802
computing integrals the major problem with this procedure is that we need to find the anti-derivative xcorresponding to given xfor some relatively simple integrands /finding xis doable taskbut it can very quickly become challengingeven impossiblethe method ( provides an exact or analytical value of the integral if we relax the requirement of the integral being exactand instead look for approximate valuesproduced by numerical methodsintegration becomes very straightforward task for any given (!the downside of numerical method is that it can only find an approximate answer leaving the exact for the approximate is mental barrier in the beginningbut remember that most real applications of integration will involve an xfunction that contains physical parameterswhich are measured with some error that isf xis very seldom exactand then it does not make sense to compute the integral with smaller error than the one already present in xanother advantage of numerical methods is that we can easily integrate function xthat is only known as samplesi discrete values at some pointsand not as continuous function of expressed through formula this is highly relevant when is measured in physical experiment basic ideas of numerical integration we consider the integral zb /dx ( most numerical methods for computing this integral split up the original integral into sum of several integralseach covering smaller part of the original integration interval oeabthis re-writing of the integral is based on selection of integration points xi that are distributed on the interval oeabintegration points mayor may notbe evenly distributed an even distribution simplifies expressions and is often sufficientso we will mostly restrict ourselves to that choice the integration points are then computed as xi ihi ( where ba ( given the integration pointsthe original integral is re-written as sum of integralseach integral being computed over the sub-interval between two consecutive integration points the integral in ( is thus expressed as hd zb zx /dx zx /dx note that and xn zxn /dx xn /dx (
3,803
proceeding from ( )the different integration methods will differ in the way they approximate each integral on the right hand side the fundamental idea is that each term is an integral over small interval oexi xi and over this small intervalit makes sense to approximate by simple shapesay constanta straight lineor parabolawhich we can easily integrate by hand the details will become clear in the coming examples computational example to understand and compare the numerical integration methodsit is advantageous to use specific integral for computations and graphical illustrations in particularwe want to use an integral that we can calculate by hand such that the accuracy of the approximation methods can easily be assessed our specific integral is taken from basic physics assume that you speed up your car from rest and wonder how far you go in seconds the distance is given by the rt integral /dtwhere tis the velocity as function of time rapidly increasing velocity function might be td ( the distance after one second is /dt( which is the integral we aim to compute by numerical methods fortunatelythe chosen expression of the velocity has form that makes it easy to calculate the anti-derivative as td ( we can therefore compute the exact value of the integral as : (rounded to decimals for convenience the composite trapezoidal rule rb the integral /dx may be interpreted as the area between the axis and the graph xof the integrand figure illustrates this area for the choice ( computing the integral /dt amounts to computing the area of the hatched region if we replace the true graph in fig by set of straight line segmentswe may view the area rather as composed of trapezoidsthe areas of which are easy to compute this is illustrated in fig where straight line segments give rise to trapezoidscovering the time intervals oe : /oe : : /oe : : and oe : : note that we have taken the opportunity here to demonstrate the computations with time intervals that differ in size
3,804
computing integrals fig the integral of interpreted as the area under the graph of fig computing approximately the integral of function as the sum of the areas of the trapezoids
3,805
the areas of the trapezoids shown in fig now constitute our approximation to the integral ( ) : : /dt : : : : : ( where : : / : : / : : / : : ( ( ( ( with td each term in ( is readily computed and our approximate computation gives /dt : ( compared to the true answer of this is off by about howevernote that we used just trapezoids to approximate the area with more trapezoidsthe approximation would have become bettersince the straight line segments in the upper trapezoid side then would follow the graph more closely doing another hand calculation with more trapezoids is not too tempting for lazy humanthoughbut it is perfect job for computerlet us therefore derive the expressions for approximating the integral by an arbitrary number of trapezoids the general formula rb for given function /we want to approximate the integral /dx by trapezoids (of equal widthwe start out with ( and approximate each integral on the right hand side with single trapezoid in detailzb zx xdx zx /dx zxn /dx /dxxn  ch :: xn xn ch (
3,806
computing integrals by simplifying the right hand side of ( we get zb xdx oef xn xn /( which is more compactly written as zb xdx xi xn ( composite integration rules the word composite is often used when numerical integration method is applied with more than one sub-interval strictly speaking thenwritinge "the trapezoidal method"should imply the use of only single trapezoidwhile "the composite trapezoidal methodis the most correct name when several trapezoids are used howeverthis naming convention is not always followedso saying just "the trapezoidal methodmay point to single trapezoid as well as the composite rule with many trapezoids implementation specific or general implementationsuppose our primary goal was to compute the specific integral /dt with td first we played around with simple hand calculation to see what the method was aboutbefore we (as one often does in mathematicsdeveloped general formula ( for the general or rb "abstractintegral /dx to solve our specific problem /dt we must then apply the general formula ( to the given data (function and integral limitsin our problem although simple in principlethe practical steps are confusing for many because the notation in the abstract problem in ( differs from the notation in our special problem clearlythe xand in ( correspond to vtand perhaps for the trapezoid width in our special problem the programmer' dilemma should we write special program for the special integralusing the ideas from the general rule ( )but replacing by vx by tand by should we implement the general method ( as it stands in general function trapezoid(fabnand solve the specific problem at hand by specialized call to this functionalternative is always the best choicethe first alternative in the box above sounds less abstract and therefore more attractive to many neverthelessas we hope will be evident from the examplesthe second alternative is actually the simplest and most reliable from both mathematical and programming point of view these authors will claim that the second
3,807
alternative is the essence of the power of mathematicswhile the first alternative is the source of much confusion about mathematicsrb implementation with functions for the integral /dx computed by the formula ( we want the corresponding python function trapezoid to take any aband as input and return the approximation to the integral we write python function trapezoidal in file trapezoidal py as close as possible to the formula ( )making sure variable names correspond to the mathematical notationdef trapezoidal(fabn) float( - )/ result * ( * (bfor in range( )result + ( *hresult * return result solving our specific problem in session just having the trapezoidal function as the only content of file trapezoidal py automatically makes that file module that we can import and test in an interactive sessionfrom trapezoidal import trapezoidal from math import exp lambda *( ** )*exp( ** numerical trapezoidal( nnumerical let us compute the exact expression and the error in the approximationv lambda texp( ** exact ( ( exact numerical - is this error convincingwe can try larger nnumerical trapezoidal( = exact numerical - - fortunatelymany more trapezoids give much smaller error solving our specific problem in program instead of computing our special problem in an interactive sessionwe can do it in program as alwaysa chunk of code doing particular thing is best isolated as function even if we do not see any future reason to call the function several times and even if we have no need for arguments to parameterize what goes on inside the function in the present case
3,808
computing integrals we just put the statements we otherwise would have put in main programinside functiondef application()from math import exp lambda *( ** )*exp( ** input(' 'numerical trapezoidal( ncompare with exact result lambda texp( ** exact ( ( error exact numerical print ' =% ferror% (nnumericalerrornow we compute our special problem by calling application(as the only statement in the main program both the trapezoidal and application functions reside in the file trapezoidal pywhich can be run as terminal terminalpython trapezoidal py = error- making module when we have the different pieces of our program as collection of functionsit is very straightforward to create module that can be imported in other programs that ishaving our code as modulemeans that the trapezoidal function can easily be reused by other programs to solve other problems the requirements of module are simpleput everything inside functions and let function calls in the main program be in the so-called test blockif __name__ ='__main__'application(the if test is true if the module filetrapezoidal pyis run as program and false if the module is imported in another program consequentlywhen we do from trapezoidal import trapezoidal in some filethe test fails and application(is not calledi our special problem is not solved and will not print anything on the screen on the other handif we run trapezoidal py in the terminal windowthe test condition is positiveapplication(is calledand we get output in the windowterminal terminalpython trapezoidal py = error- -
3,809
alternative flat special-purpose implementation let us illustrate the implementation implied by alternative in the programmer' dilemma box in sect that iswe make special-purpose code where we adapt the general formula ( to the specific problem dt basicallywe use for loop to compute the sum each term with xin the formula ( is replaced by by tand by first try at writing plainflat program doing the special calculation is from math import exp input(' 'dt float( )/ integral by the trapezoidal method numerical * *( ** )*exp( ** * *( ** )*exp( ** for in range( )numerical + *(( *dt)** )*exp(( *dt)** numerical *dt exact_value exp( ** exp( ** error abs(exact_value numericalrel_error (error/exact_value)* print ' =% ferror% (nnumericalerrorthe problem with the above code is at least three-fold we need to reformulate ( for our special problem with different notation the integrand is inserted many times in the codewhich quickly leads to errors lot of edits are necessary to use the code to compute different integral these edits are likely to introduce errors the potential errors involved in point serve to illustrate how important it is to use python functions as mathematical functions here we have chosen to use the lambda function to define the integrand as the variable vfrom math import exp lambda *( ** )*exp( ** input(' 'dt float( )/ function to be integrated replacing by is not strictly required as many use as interval also along the time axis neverthelesst is an even more popular notation for small time intervalso we adopt that common notation
3,810
computing integrals integral by the trapezoidal method numerical * ( * (bfor in range( )numerical + ( *dtnumerical *dt lambda texp( ** exact_value (bf(aerror abs(exact_value numericalrel_error (error/exact_value)* print ' =% ferror% (nnumericalerrorunfortunatelythe two other problems remain and they are fundamental : suppose you want to compute another integralsay dx how much do we need to change in the previous code to compute the new integralnot so muchthe formula for must be replaced by new formula the limits and the anti-derivative is not easily known and can be omittedand therefore we cannot write out the error the notation should be changed to be aligned with the new problemi and dt changed to and these changes are straightforward to implementbut they are scattered around in the programa fact that requires us to be very careful so we do not introduce new programming errors while we modify the code it is also very easy to forget to make required change with the previous code in trapezoidal pywe can compute the new integral : dx without touching the mathematical algorithm in an interactive session (or in programwe can just do from trapezoidal import trapezoidal from math import exp trapezoidal(lambda xexp(- ** )- when you now look back at the two solutionsthe flat special-purpose program and the function-based program with the general-purpose function trapezoidalyou hopefully realize that implementing general mathematical algorithm in general function requires somewhat more abstract thinkingbut the resulting code can be used over and over again essentiallyif you apply the flat special-purpose styleyou have to retest the implementation of the algorithm after every change of the program you cannot integrate by handbut this particular integral is appearing so often in so many contexts that the integral is special functioncalled the error function (wiki/error_functionand written erf xin codeyou can call erf(xthe erf function is found in the math module
3,811
the present integral problems result in short code in more challenging engineering problems the code quickly grows to hundreds and thousands of lines without abstractions in terms of general algorithms in general reusable functionsthe complexity of the program grows so fast that it will be extremely difficult to make sure that the program works properly another advantage of packaging mathematical algorithms in functions is that function can be reused by anyone to solve problem by just calling the function with proper set of arguments understanding the function' inner details is not necessary to compute new integral similarlyyou can find libraries of functions on the internet and use these functions to solve your problems without specific knowledge of every mathematical detail in the functions this desirable feature has its downsideof coursethe user of function may misuse itand the function may contain programming errors and lead to wrong answers testing the output of downloaded functions is therefore extremely important before relying on the results the composite midpoint method the idea rather than approximating the area under curve by trapezoidswe can use plain rectangles (fig it may sound less accurate to use horizontal lines and not skew lines following the function to be integratedbut an integration method based on rectangles (the midpoint methodis in fact slightly more accurate than the one based on trapezoidsfig computing approximately the integral of function as the sum of the areas of the rectangles
3,812
computing integrals in the midpoint methodwe construct rectangle for every sub-interval where the height equals at the midpoint of the sub-interval let us do this for four rectanglesusing the same sub-intervals as we had for hand calculations with the trapezoidal methodoe : /oe : : /oe : : /and oe : : we get : : : /dt : : : : ( where and are the widths of the sub-intervalsused previously with the trapezoidal method and defined in ( )-( with td the approximation becomes compared with the true answer ( )this is about too smallbut it is better than what we got with the trapezoidal method ( %with the same sub-intervals more rectangles give better approximation the general formula let us derive formula for the midpoint method based on rectangles of equal widthzb zx xdx zx /dx zxn /dx xn xn xn hf hf hf (  xn xn cf :::  ( /dx this sum may be written more compactly as zb /dx where xi ih xi /(
3,813
implementation we follow the advice and lessons learned from the implementation of the trapezoidal method and make function midpoint(fabn(in file midpoint pyfor implementing the general formula ( )def midpoint(fabn) float( - )/ result for in range( )result + (( / *hresult * return result we can test the function as we explained for the similar trapezoidal method the error in our particular problem dt with four intervals is now about in contrast to for the trapezoidal rule this is in fact not accidentalone can show mathematically that the error of the midpoint method is bit smaller than for the trapezoidal method the differences are seldom of any practical importanceand on laptop we can easily use and get the answer with an error of about in couple of seconds comparing the trapezoidal and the midpoint methods the next example shows how easy we can combine the trapezoidal and midpoint functions to make comparison of the two methods in the file compare_ integration_methods pyfrom trapezoidal import trapezoidal from midpoint import midpoint from math import exp lambda yexp(- ** print midpoint trapezoidalfor in range( ) ** midpoint(gabnt trapezoidal(gabnprint '% (nmtnote the efforts put into nice formatting the output becomes midpoint trapezoidal
3,814
computing integrals visual inspection of the numbers shows how fast the digits stabilize in both methods it appears that digits have stabilized in the last two rows remark the trapezoidal and midpoint methods are just two examples in jungle of numerical integration rules other famous methods are simpson' rule and gauss quadrature they all work in the same wayzb /dx wi xi that isthe integral is approximated by sum of function evaluationswhere each evaluation xi is given weight wi the different methods differ in the way they construct the evaluation points xi and the weights wi we have used equally spaced points xi but higher accuracy can be obtained by optimizing the location of xi testing problems with brief testing procedures testing of the programs for numerical integration has so far employed two strategies if we have an exact answerwe compute the error and see that increasing decreases the error when the exact answer is not availablewe can (as in the comparison example in the previous sectionlook at the integral values and see that they stabilize as grows unfortunatelythese are very weak test procedures and not at all satisfactory for claiming that the software we have produced is correctly implemented to see thiswe can introduce bug in the application function that calls trapezoidalinstead of integrating we write "accidentally but keep the same anti-derivative / for computing the error with the bug and
3,815
the error is but without the bug the error is it is of course completely impossible to tell if is the right value of the error fortunatelyincreasing shows that the error stays about in the program with the bugso the test procedure with increasing and checking that the error decreases points to problem in the code let us look at another bugthis time in the mathematical algorithminstead of computing ac /as we shouldwe forget the second and write : * (af(bthe error for when computing : dt goes like respectivelywhich looks promising the problem is that the right errors should be and that isthe error should be reduced faster in the correct than in the buggy code the problemhoweveris that it is reduced in both codesand we may stop further testing and believe everything is correctly implemented unit testing good habit is to test small pieces of larger code individuallyone at time this is known as unit testing one identifies (smallunit of the codeand then one makes separate test for this unit the unit test should be stand-alone in the sense that it can be run without the outcome of other tests typicallyone algorithm in scientific programs is considered as unit the challenge with unit tests in numerical computing is to deal with numerical approximation errors fortunate side effect of unit testing is that the programmer is forced to use functions to modularize the code into smallerlogical pieces proper test procedures there are three serious ways to test the implementation of numerical methods via unit tests comparing with hand-computed results in problem with few arithmetic operationsi small solving problem without numerical errors we know that the trapezoidal rule must be exact for linear functions the error produced by the program must then be zero (to machine precision demonstrating correct convergence rates strong test when we can compute exact errorsis to see how fast the error goes to zero as grows in the trapezoidal and midpoint rules it is known that the error depends on as as hand-computed results let us use two trapezoids and compute the integral / td : / : / : when : is the width of the two trapezoids running the program gives exactly the same result
3,816
computing integrals solving problem without numerical errors the best unit tests for numerical algorithms involve mathematical problems where we know the numerical result beforehand usuallynumerical results contain unknown approximation errorsso knowing the numerical result implies that we have problem where the approximation errors vanish this feature may be present in very simple mathematical problems for examplethe trapezoidal method is exact for integration of linear functions xd ax we can therefore pick some linear function and construct test function that checks equality between the exact analytical expression for the integral and the number computed by the implementation of the trapezoidal method : specific test case can be : /dx this integral involves an "arbitraryinterval oe : : and an "arbitrarylinear function xd by "arbitrarywe mean expressions where we avoid the special numbers and since these have special properties in arithmetic operations ( forgetting to multiply is equivalent to multiplying by and forgetting to add is equivalent to adding demonstrating correct convergence rates normallyunit tests must be based on problems where the numerical approximation errors in our implementation remain unknown howeverwe often know or may assume certain asymptotic behavior of the error we can do some experimental runs with the test problem dt where is doubled in each runn the corresponding errors are then % and %respectively these numbers indicate that the error is roughly reduced by factor of when doubling thusthe error converges to zero as and we say that the convergence rate is in factthis result can also be shown mathematically for the trapezoidal and midpoint method numerical integration methods usually have an error that converge to zero as np for some that depends on the method with such resultit does not matter if we do not know what the actual approximation error iswe know at what rate it is reducedso running the implementation for two or more different values will put us in position to measure the expected rate and see if it is achieved the idea of corresponding unit test is then to run the algorithm for some valuescompute the error (the absolute value of the difference between the exact analytical result and the one produced by the numerical method)and check that the error has approximately correct asymptotic behaviori that the error is proportional to in case of the trapezoidal and midpoint method let us develop more precise method for such unit tests based on convergence rates we assume that the error depends on according to nr where is an unknown constant and is the convergence rate consider set of experiments with various nn nq we compute the corresponding errors eq for two consecutive experimentsnumber and we have the error model ei nri ei nri ( (
3,817
these are two equations for two unknowns and we can easily eliminate by dividing the equations by each other then solving for gives ri ln ei =ei ln ni =ni ( we have introduced subscript in since the estimated value for varies with hopefullyri approaches the correct convergence rate as the number of intervals increases and finite precision of floating-point numbers the test procedures above lead to comparison of numbers for checking that calculations were correct such comparison is more complicated than what newcomer might think suppose we have calculation and want to check that the result is what we expect we start with expected =expected true then we proceed with expected =expected false so why is : : $ : the reason is that real numbers cannot in general be exactly represented on computer they must instead be approximated by floating-point number that can only store finite amount of informationusually about digits of real number let us print and with decimalsprint ' \ \ \ ( we see that all of the numbers have an inaccurate digit in the th decimal place because evaluates to and is represented as these two numbers are not equal in generalreal numbers in python have (at most correct decimals when we compute with real numbersthese numbers are inaccurately represented on the computerand arithmetic operations with inaccurate numbers lead to small rounding errors in the final results depending on the type of numerical algorithmthe rounding errors may or may not accumulate
3,818
computing integrals if we cannot make tests like = what should we then dothe answer is that we must accept some small inaccuracy and make test with tolerance here is the recipea expected computed diff abs(expected computedtol - diff tol true here we have set the tolerance for comparison to but calculating ( shows that it equals - - so lower tolerance could be used in this particular example howeverin other calculations we have little idea about how accurate the answer is (there could be accumulation of rounding errors in more complicated algorithms)so or are robust values as we demonstrate belowthese tolerances depend on the magnitude of the numbers in the calculations doing an experiment with : : : for shows that the answer (which should be zerois around this means that the tolerance must be larger if we compute with larger numbers setting proper tolerance therefore requires some experiments to see what level of accuracy one can expect way out of this difficulty is to work with relative instead of absolute differences in relative difference we divide by one of the operandse : : : /cd ab computing this for various shows value around safer procedure is thus to use relative differences constructing unit tests and writing test functions python has several frameworks for automatically running and checking potentially very large number of tests for parts of your software by one command this is an extremely useful feature during program developmentwhenever you have done some changes to one or more fileslaunch the test command and make sure nothing is broken because of your edits the test frameworks nose and py test are particularly attractive as they are very easy to use tests are placed in special test functions that the frameworks can recognize and run for you the requirements to test function are simplethe name must start with test_ the test function cannot have any arguments the tests inside test functions must be boolean expressions boolean expression must be tested with assert bmsgwhere msg is an optional object (string or numberto be written out when is false
3,819
suppose we have written function def add(ab)return corresponding test function can then be def test_add(expected computed add( assert computed =expected' + =%gcomputed test functions can be in any program file or in separate filestypically with names starting with test you can also collect tests in subdirectoriesrunning py test - - will actually run all tests in all testpy files in all subdirectorieswhile nosetests - - restricts the attention to subdirectories whose names start with test or end with _test or _tests as long as we add integersthe equality test in the test_add function is appropriatebut if we try to call add( insteadwe will face the rounding error problems explained in sect and we must use test with tolerance insteaddef test_add(expected computed add( tol - diff abs(expected computedassert diff tol'diff=%gdiff below we shall write test functions for each of the three test procedures we suggestedcomparison with hand calculationschecking problems that can be exactly solvedand checking convergence rates we stick to testing the trapezoidal integration code and collect all test functions in one common file by the name test_trapezoidal py hand-computed numerical results our previous hand calculations for two trapezoids can be checked against the trapezoidal function inside test function (in file test_trapezoidal py)from trapezoidal import trapezoidal def test_trapezoidal_one_exact_result()"""compare one hand-computed result ""from math import exp lambda *( ** )*exp( ** computed trapezoidal( nexpected error abs(expected computedtol - success error tol msg 'error=% tol=% (errrortolassert successmsg
3,820
computing integrals note the importance of checking err against exact with tolerancerounding errors from the arithmetics inside trapezoidal will not make the result exactly like the hand-computed one the size of the tolerance is here set to which is kind of all-round value for computations with numbers not deviating much from unity solving problem without numerical errors we know that the trapezoidal rule : is exact for linear integrands choosing the integral : /dx as test casethe corresponding test function for this unit test may look like def test_trapezoidal_linear()"""check that linear functions are integrated exactly "" lambda * lambda * ** * anti-derivative expected (bf(atol - for in computed trapezoidal(fabnerror abs(expected computedsuccess error tol msg ' =%derr=% (nerrorassert successmsg demonstrating correct convergence rates in the present example with integrationit is known that the approximation errors in the trapezoidal rule are proportional to being the number of subintervals used in the composite rule computing convergence rates requires somewhat more tedious programming than the previous testsbut can be applied to more general integrands the algorithm typically goes like for ni compute integral with ni intervals compute the error ei estimate ri from ( if the corresponding code may look like def convergence_rates(ffabnum_experiments= )from math import log from numpy import zeros expected (bf(an zeros(num_experimentsdtype=inte zeros(num_experimentsr zeros(num_experiments- for in range(num_experiments) [ **( + computed trapezoidal(fabn[ ] [iabs(expected computedif r_im log( [ ]/ [ - ])/log(float( [ ])/ [ - ] [ - float(' fr_im truncate to two decimals return
3,821
making test function is matter of choosing ffaand band then checking the value of ri for the largest idef test_trapezoidal_conv_rate()"""check empirical convergence rates against the expected - ""from math import exp lambda *( ** )*exp( ** lambda texp( ** convergence_rates(vvab print tol msg str( [- :]show last estimated rates assert (abs( [- ] tolmsg running the test shows that all ri except the first oneequal the target limit within two decimals this observation suggest tolerance of remark about version control of files having suite of test functions for automatically checking that your software works is considered as fundamental requirement for reliable computing equally important is system that can keep track of different versions of the files and the testsknown as version control system today' most popular version control system is git which the authors strongly recommend the reader to use for programming and writing reports the combination of git and cloud storage such as github is very common way of organizing scientific or engineering work we have quick intro to git and github that gets you up and running within minutes the typical workflow with git goes as follows before you start working with filesmake sure you have the latest version of them by running git pull edit filesremove or create files (new files must be registered by git add when natural piece of work is donecommit your changes by the git commit command implement your changes also in the cloud by doing git push nice feature of git is that people can edit the same file at the same time and very often git will be able to automatically merge the changes (!thereforeversion control is crucial when you work with others or when you do your work on different types of computers another key feature is that anyone can at any time view the history of filesee who did what whenand roll back the entire file collection to previous commit this feature isof coursefundamental for reliable work
3,822
computing integrals vectorization the functions midpoint and trapezoid usually run fast in python and compute an integral to satisfactory precision within fraction of second howeverlong loops in python may run slowly in more complicated implementations to increase the speedthe loops can be replaced by vectorized code the integration functions constitute simple and good example to illustrate how to vectorize loops we have already seen simple examples on vectorization in sect when we could evaluate mathematical function xfor large number of values stored in an array basicallywe can write def ( )return exp(- )*sin( * from numpy import expsinlinspace linspace( coordinates from intervals on [ (xall points evaluated at once the result is the array that would be computed if we ran for loop over the individual values and called for each value vectorization essentially eliminates this loop in python ( the looping over and application of to each value are instead performed in library with fastcompiled codevectorizing the midpoint rule the aim of vectorizing the midpoint and trapezoidal functions is also to remove the explicit loop in python we start with vectorizing the midpoint function since trapezoid is not equally straightforward the fundamental ideas of the vectorized algorithm are to compute all the evaluation points in one array call (xto produce an array of corresponding function values use the sum function to sum the (xvalues the evaluation points in the midpoint method are xi /hi that isn uniformly distributed coordinates between = and = such coordinates can be calculated by linspace( + / - / ngiven that the python implementation of the mathematical function works with an array argumentwhich is very often the case in pythonf(xwill produce all the function values in an array the array elements are then summed up by sumsum( ( )this sum is to be multiplied by the rectangle width to produce the integral value the complete function is listed below from numpy import linspacesum def midpoint(fabn) float( - )/ linspace( / / nreturn *sum( ( )the code is found in the file integration_methods_vec py
3,823
let us test the code interactively in python shell to compute dt the file with the code above has the name integration_methods_vec py and is valid module from which we can import the vectorized functionfrom integration_methods_vec import midpoint from numpy import exp lambda * ** *exp( ** midpoint( note the necessity to use exp from numpyour function will be called with as an arrayand the exp function must be capable of working with an array the vectorized code performs all loops very efficiently in compiled coderesulting in much faster execution moreovermany readers of the code will also say that the algorithm looks clearer than in the loop-based implementation vectorizing the trapezoidal rule we can use the same approach to vectorize the trapezoid function howeverthe trapezoidal rule performs sum where the end points have different weight if we do sum( ( ))we get the end points (aand (bwith weight unity instead of one half remedy is to subtract the error from sum( ( ))sum( ( ) * ( * (bthe vectorized version of the trapezoidal method then becomes def trapezoidal(fabn) float( - )/ linspace(abn+ sum( ( ) * ( * (breturn * measuring computational speed now that we have created fastervectorized versions of functions in the previous sectionit is interesting to measure how much faster they are the purpose of the present section is therefore to explain how we can record the cpu time consumed by function so we can answer this question there are many techniques for measuring the cpu time in pythonand here we shall just explain the simplest and most convenient onethe %timeit command in ipython the following interactive session should illustrate competition where the vectorized versions of the functions are supposed to winin [ ]from integration_methods_vec import midpoint as midpoint_vec in [ ]from midpoint import midpoint in [ ]from numpy import exp in [ ] lambda * ** *exp( **
3,824
computing integrals in [ ]%timeit midpoint_vec( loopsbest of ms per loop in [ ]%timeit midpoint( loopsbest of per loop in [ ] /( * out[ ] efficiency factor we see that the vectorized version is about times faster ms versus the results for the trapezoidal method are very similarand the factor of about is independent of the number of intervals double and triple integrals the midpoint rule for double integral given double integral over rectangular domain oeaboecd zb zd xy/dydxa how can we approximate this integral by numerical methodsderivation via one-dimensional integrals since we know how to deal with integrals in one variablea fruitful approach is to view the double integral as two integralseach in one variablewhich can be approximated numerically by previous one-dimensional formulas to this endwe introduce help function xand write zb zd zb xy/dydx zd xd /dxa xy/dy each of the integrals zb zd /dxg xd xy/dy can be discretized by any numerical integration rule for an integral in one variable rd let us use the midpoint method ( and start with xd xy/dy we introduce ny intervals on oecd with length hy the midpoint rule for this integral then becomes zd xd ny xy/dy hy xyj / yj hy hy
3,825
double and triple integrals the expression looks somewhat different from ( )but that is because of the notationsince we integrate in the direction and will have to work with both and as coordinateswe must use ny for nhy for hand the counter is more naturally called when integrating in integrals in the direction will use hx and nx for and nand as counter rb the double integral is /dxwhich can be approximated by the midpoint methodzb nx /dx hx xi /xi hx ihx putting the formulas togetherwe arrive at the composite midpoint method for double integralzb zd xy/dydx hx nx ny hy xi yj hy hx hx hy ac ihx hy nx ( direct derivation the formula ( can also be derived directly in the twodimensional case by applying the idea of the midpoint method we divide the rectangle oeaboecd into nx ny equal-sized cells the idea of the midpoint method is to approximate by constant over each celland evaluate the constant at the midpoint cell ij occupies the area oea ihx /hx oec hy /hy and the midpoint is xi yj with xi ihx hx yj hy hy the integral over the cell is therefore hx hy xi yj /and the total double integral is the sum over all cellswhich is nothing but formula ( programming double sum the formula ( involves double sumwhich is normally implemented as double for loop python function implementing ( may look like def midpoint_double (fabcdnxny)hx ( )/float(nxhy ( )/float(nyi for in range(nx)for in range(ny)xi hx/ *hx yj hy/ *hy +hx*hy* (xiyjreturn
3,826
computing integrals if this function is stored in module file midpoint_double pywe can compute some integrale cy/dxdy in an interactive shell and demonstrate that the function computes the right numberfrom midpoint_double import midpoint_double def (xy)return * midpoint_double ( reusing code for one-dimensional integrals it is very natural to write twodimensional midpoint method as we did in function midpoint_double when we have the formula ( howeverwe could alternatively askmuch as we did in the mathematicscan we reuse well-tested implementation for one-dimensional integrals to compute double integralsthat iscan we use function midpoint def midpoint(fabn) float( - )/ result for in range( )result + (( / *hresult * return result from sect "twice"the answer is yesif we think as we did in the mathematicscompute the double integral as midpoint rule for integrating xand define xi in terms of midpoint rule over in the coordinate the corresponding function has very short codedef midpoint_double (fabcdnxny)def ( )return midpoint(lambda yf(xy)cdnyreturn midpoint(gabnxthe important advantage of this implementation is that we reuse well-tested function for the standard one-dimensional midpoint rule and that we apply the onedimensional rule exactly as in the mathematics verification via test functions how can we test that our functions for the double integral workthe best unit test is to find problem where the numerical approximation error vanishes because then we know exactly what the numerical answer should be the midpoint rule is exact for linear functionsregardless of how many subinterval we use alsoany linear two-dimensional function xyd px qy will be integrated exactly by the two-dimensional midpoint rule we may pick xyd and create proper test function that can automatically verify our two alternative implementations of the two-dimensional midpoint rule to compute the integral of xywe take advantage of sympy to eliminate the possibility of errors in hand calculations the test function becomes
3,827
double and triple integrals def test_midpoint_double()"""test that linear function is integrated exactly ""def (xy)return * import sympy xy sympy symbols(' 'i_expected sympy integrate( (xy)(xab)(ycd)test three casesnx ny for nxny in ( )( )( )i_computed midpoint_double (fabcdnxnyi_computed midpoint_double (fabcdnxnytol - #print i_expectedi_computed i_computed assert abs(i_computed i_expectedtol assert abs(i_computed i_expectedtol let test functions speak upif we call the above test_midpoint_double function and nothing happensour implementations are correct howeverit is somewhat annoying to have function that is completely silent when it works are we sure all things are properly computedduring development it is therefore highly recommended to insert print statement such that we can monitor the calculations and be convinced that the test function does what we want since test function should not have any print statementwe simply comment it out as we have done in the function listed above the trapezoidal method can be used as alternative for the midpoint method the derivation of formula for the double integral and the implementations follow exactly the same ideas as we explained with the midpoint methodbut there are more terms to write in the formulas exercise asks you to carry out the details that exercise is very good test on your understanding of the mathematical and programming ideas in the present section the midpoint rule for triple integral theory once method that works for one-dimensional problem is generalized to two dimensionsit is usually quite straightforward to extend the method to three dimensions this will now be demonstrated for integrals we have the triple integral zb zd zf xyz/dzdydx
3,828
computing integrals and want to approximate the integral by midpoint rule following the ideas for the double integralwe split this integral into one-dimensional integralszf xyd xyz/dz zd xd xy/dy zb zd zf zb xyz/dzdydx /dx for each of these one-dimensional integrals we apply the midpoint rulezf xyz/dz xyd zd ny xy/dy xd zb zd zf xyj / zb xyz/dzdydx xyzk /kd nx /dx zk hz khz yj hy hy nx xi / where starting with the formula for previous formulas gives rb rd rf xi hx ihx xyz/dzdydx and inserting the two zb zd zf xyzdzdydx hx hy hz nz nx kd hx ihx hy hy hz khz ( note that we may apply the ideas under direct derivation at the end of sect to arrive at ( directlydivide the domain into nx ny nz cells of volumes hx hy hz approximate by constantevaluated at the midpoint xi yj zk /in each celland sum the cell integrals hx hy hz xi yj zk
3,829
double and triple integrals implementation we follow the ideas for the implementations of the midpoint rule for double integral the corresponding functions are shown below and found in the file midpoint_triple py def midpoint_triple (gabcdefnxnynz)hx ( )/float(nxhy ( )/float(nyhz ( )/float(nzi for in range(nx)for in range(ny)for in range(nz)xi hx/ *hx yj hy/ *hy zk hz/ *hz +hx*hy*hz* (xiyjzkreturn def midpoint(fabn) float( - )/ result for in range( )result + (( / *hresult * return result def midpoint_triple (gabcdefnxnynz)def (xy)return midpoint(lambda zg(xyz)efnzdef ( )return midpoint(lambda yp(xy)cdnyreturn midpoint(qabnxdef test_midpoint_triple()"""test that linear function is integrated exactly ""def (xyz)return * * - import sympy xyz sympy symbols(' 'i_expected sympy integrateg(xyz)(xab)(ycd)(zef)for nxnynz in ( )( )( )i_computed midpoint_triple gabcdefnxnynzi_computed midpoint_triple gabcdefnxnynztol - print i_expectedi_computed i_computed assert abs(i_computed i_expectedtol assert abs(i_computed i_expectedtol if __name__ ='__main__'test_midpoint_triple(
3,830
computing integrals monte carlo integration for complex-shaped domains repeated use of one-dimensional integration rules to handle double and triple integrals constitute working strategy only if the integration domain is rectangle or box for any other shape of domaincompletely different methods must be used common approach for twoand three-dimensional domains is to divide the domain into many small triangles or tetrahedra and use numerical integration methods for each triangle or tetrahedron the overall algorithm and implementation is too complicated to be addressed in this book insteadwe shall employ an alternativevery simple and general methodcalled monte carlo integration it can be implemented in half page of codebut requires orders of magnitude more function evaluations in double integrals compared to the midpoint rule howevermonte carlo integration is much more computationally efficient than the midpoint rule when computing higher-dimensional integrals in more than three variables over hypercube domains our ideas for double and triple integrals can easily be generalized to handle an integral in variables midpoint formula then involves sums with cells in each coordinate directionthe formula requires nm function evaluations that isthe computational work explodes as an exponential function of the number of space dimensions monte carlo integrationon the other handdoes not suffer from this explosion of computational work and is the preferred method for computing higher-dimensional integrals soit makes sense in on numerical integration to address monte carlo methodsboth for handling complex domains and for handling integrals with many variables the monte carlo integration algorithm the idea of monte carlo integration of rb is to use the mean-value theorem from calculuswhich states that the /dx rb integral /dx equals the length of the integration domainhere batimes the average value of fnin oeabthe average value can be computed by sampling at set of random points inside the domain and take the mean of the function values in higher dimensionsan integral is estimated as the area/volume of the domain times the average valueand again one can evaluate the integrand at set of random points in the domain and compute the mean value of those evaluations let us introduce some quantities to help us make the specification of the integration algorithm more precise suppose we have some two-dimensional integral xy/dxdxwhere is two-dimensional domain defined via help function xy/ xyj xy that ispoints xyfor which xy lie inside "and points for which xyare outside the boundary of the domain @is given by the implicit curve xyd such formulations of geometries have been very common during the last couple of decadesand one refers to as level-set function and the
3,831
double and triple integrals boundary as the zero-level contour of the level-set function for simple geometries one can easily construct by handwhile in more complicated industrial applications one must resort to mathematical models for constructing let "be the area of domain we can estimate the integral by this monte carlo integration method embed the geometry in rectangular area draw large number of random points xyin count the fraction of points that are inside approximate "/= rby qi set " qa evaluate the mean of fnat the points inside estimate the integral as "/fn note that ris trivial to compute since is rectanglewhile "is unknown howeverif we assume that the fraction of roccupied by "is the same as the fraction of random points inside "we get simple estimate for "to get an idea of the methodconsider circular domain embedded in rectangle as shown below collection of random points is illustrated by black dots implementation python function implementing xy/dxdy can be written like thisimport numpy as np def montecarlo_double(fgx )""monte carlo integration of over domain >= embedded in rectangle [ , ] [ , ^ is the number of random points ""
3,832
computing integrals draw ** random points in the rectangle np random uniform( ny np random uniform( ncompute sum of values inside the integration domain f_mean num_inside number of , points inside domain ( >= for in range(len( ))for in range(len( ))if ( [ ] [ ]> num_inside + f_mean + ( [ ] [ ]f_mean f_mean/float(num_insidearea num_inside/float( ** )*( )*( return area*f_mean (see the file mc_double py verification simple test case is to check the area of rectangle oe oe : embedded in rectangle oe oe the right answer is but monte carlo integration isunfortunatelynever exact so it is impossible to predict the output of the algorithm all we know is that the estimated integral should approach as the number of random points goes to infinity alsofor fixed number of pointswe can run the algorithm several times and get different numbers that fluctuate around the exact valuesince different sample points are used in different calls to the monte carlo integration algorithm : the area of the rectangle can be computed by the integral dydxso in this case we identify xyd and the function can be specified as ( if xyis inside oe oe : and otherwise here is an example on how we can utilize the montecarlo_double function to compute the area for different number of samplesfrom mc_double import montecarlo_double def (xy)return ( if ( < < and < < else - montecarlo_double(lambda xy montecarlo_double(lambda xy montecarlo_double(lambda xy montecarlo_double(lambda xy montecarlo_double(lambda xy montecarlo_double(lambda xy we see that the values fluctuate around fact that supports correct implementationbut in principlebugs could be hidden behind the inaccurate answers it is mathematically known that the standard deviation of the monte carlo estimate of an integral converges as = where is the number of samples this
3,833
double and triple integrals kind of convergence rate estimate could be used to verify the implementationbut this topic is beyond the scope of this book test function for function with random numbers to make test functionwe need unit test that has identical behavior each time we run the test this seems difficult when random numbers are involvedbecause these numbers are different every time we run the algorithmand each run hence produces (slightlydifferent result standard way to test algorithms involving random numbers is to fix the seed of the random number generator then the sequence of numbers is the same every time we run the algorithm assuming that the montecarlo_double function workswe fix the seedobserve certain resultand take this result as the correct result provided the test function always uses this seedwe should get exactly this result every time the montecarlo_double function is called our test function can then be written as shown below def test_montecarlo_double_rectangle_area()"""check the area of rectangle ""def (xy)return ( if ( < < and < < else - embedded rectangle np random seed( must fix the seedi_expected computed with this seed i_computed montecarlo_doublelambda xy gx nassert abs(i_expected i_computed - (see the file mc_double py integral over circle the test above involves trivial function xyd we should also test non-constant function and more complicated domain let be circle at the origin with radius and let ry this choice makes it possible to compute an exact resultin polar coordinatesf xy/dxdy simplir fies to dr = we must be prepared for quite crude approximations that fluctuate around this exact result as in the test case abovewe experience better results with larger number of points when we have such evidence for working implementationwe can turn the test into proper test function here is an exampledef test_montecarlo_double_circle_r()"""check the integral of over circle with radius ""def (xy)xcyc center radius return ** (( -xc)** ( -yc)** exactintegral of * *dr over circle with radius becomes *pi* / * ** import sympy sympy symbols(' 'i_exact sympy integrate( *sympy pi* * ( )
3,834
computing integrals print 'exact integral:'i_exact evalf( - - np random seed( i_expected computed with this seed i_computed montecarlo_doublelambda xynp sqrt( ** ** )gx nprint 'mc approximation % samples) ( ** i_computedassert abs(i_expected i_computed - (see the file mc_double py exercises exercise hand calculations for the trapezoidal method compute by hand the area composed of two trapezoids (of equal widththat apr proximates the integral dx make test function that calls the trapezoidal function in trapezoidal py and compares the return value with the handcalculated value filenametrapezoidal_test_func py exercise hand calculations for the midpoint method compute by hand the area composed of two rectangles (of equal widththat apr proximates the integral dx make test function that calls the midpoint function in midpoint py and compares the return value with the hand-calculated value filenamemidpoint_test_func py exercise compute simple integral apply the trapezoidal and midpoint functions to compute the integral /dx with and subintervals compute the error too filenameintegrate_parabola py exercise hand-calculations with sine integrals rb we consider integrating the sine function sin /dx alet and use two intervals in the trapezoidal and midpoint method compute the integral by hand and illustrate how the two numerical methods approximates the integral compare with the exact value bdo awhen filenameintegrate_sine pdf exercise make test functions for the midpoint method modify the file test_trapezoidal py such that the three tests are applied to the function midpoint implementing the midpoint method for integration filenametest_midpoint py
3,835
exercise explore rounding errors with large numbers the trapezoidal method integrates linear functions exactlyand this property was used in the test function test_trapezoidal_linear in the file test_ trapezoidal py change the function used in sect to xd and rerun the test what happenshow must you change the test to make it usefulhow does the convergence rate test behaveany need for adjustmentfilenametest_trapezoidal py exercise write test functions for xdx we want to test how the trapezoidal function works for the integral xdx two of the tests in test_trapezoidal py are meaningful for this integral compute by hand the result of using or trapezoids and modify the test_ trapezoidal_one_exact_result function accordingly then modify test_ trapezoidal_conv_rate to handle the square root integral filenametest_trapezoidal py remarks the convergence rate test fails printing out shows that the actual convergence rate for this integral is : and not the reason is that the error in the trapezoidal is / for some (unknown oeabwith method xd xf  as pointing to potential problem in the size of the error running test with say : xdx shows that the convergence rate is indeed restored to exercise rectangle methods the midpoint method divides the interval of integration into equal-sized subintervals and approximates the integral in each subinterval by rectangle whose height equals the function value at the midpoint of the subinterval insteadone might use either the left or right end of the subinterval as illustrated in fig this defines rectangle method of integration the height of the rectangle can be based on the left or right end or the midpoint fig illustration of the rectangle method with evaluating the rectangle height by either the left or right point
3,836
computing integrals awrite function rectangle(fabnheight='left'for computing rb an integral /dx by the rectangle method with height computed based on the value of heightwhich is either leftrightor mid bwrite three test functions for the three unit test procedures described in sect make sure you test for height equal to leftrightand mid you may call the midpoint function for checking the result when height=mid hint edit test_trapezoidal py filenamerectangle_methods py exercise adaptive integration suppose we want to use the trapezoidal or midpoint method to compute an integral rb /dx with an error less than prescribed tolerance what is the appropriate size of nto answer this questionwe may enter an iterative procedure where we compare the results produced by and intervalsand if the difference is smaller than the value corresponding to is returned otherwisewe halve and repeat the procedure hint it may be good idea to organize your code so that the function adaptive_ integration can be used easily in future programs you write awrite function adaptive_integration(fabepsmethod=midpointthat implements the idea above (eps corresponds to the tolerance and method can be midpoint or trapezoidalr btest the method on dx and xdx for and write out the exact error cmake plot of versus oe for xdx use logarithmic scale for filenameadaptive_integration py remarks the type of method explored in this exercise is called adaptivebecause it tries to adapt the value of to meet given error criterion the true error can very seldom be computed (since we do not know the exact answer to the computational problem)so one has to find other indicators of the errorsuch as the one here where the changes in the integral valueas the number of intervals is doubledis taken to reflect the error exercise integrating raised to consider the integral dx
3,837
the integrand does not have an anti-derivative that can be expressed in terms of standard functions (visit convince yourself that our claim is right note that wolfram alpha does give you an answerbut that answer is an approximationit is not exact this is because wolfram alpha too uses numerical methods to arrive at the answerjust as you will in this exercisethereforewe are forced to compute the integral by numerical methods compute result that is right to four digits hint use ideas from exercise filenameintegrate_x py exercise integrate products of sine functions in this exercise we shall integrate ij; sin jxsin kx/dx where and are integers aplot sin xsin xand in separate plots exr sin xsin xfor plain why you expect sin sin dx and sin sin dx buse the trapezoidal rule to compute ij; for and filenameproducts_sines py exercise revisit fit of sines to function this is continuation of exercise the task is to approximate given function ton oeby sum of sinessn td bn sin nt( nd we are now interested in computing the unknown coefficients bn such that sn tis in some sense the best approximation to tone common way of doing this is to first set up general expression for the approximation errormeasured by "summing upthe squared deviation of sn from ed sn // dt we may view as function of bn minimizing with respect to bn will give us best approximationin the sense that we adjust bn such that sn deviates as little as possible from
3,838
computing integrals minimization of function of variablese bn is mathematically performed by requiring all the partial derivatives to be zero@ @ @ @ :@ @bn acompute the partial derivative @ =@ and generalize to the arbitrary case @ =@bn bshow that bn tsin ntdt cwrite function integrate_coeffs(fnmthat computes bn by numerical integrationusing intervals in the trapezoidal rule da remarkable property of the trapezoidal rule is that it is exact for integrals use this property to sin nt dt (when subintervals are of equal sizecreate function test_integrate_coeff to verify the implementation of integrate_coeffs eimplement the choice td as python function (tand call integrate_coeffs( to see what the optimal choice of is fmake function plot_approx(fnmfilenamewhere you plot (ttogether with the best approximation sn as computed aboveusing intervals for numerical integration save the plot to file with name filename grun plot_approx(fnmfilenamefor td for observe how the approximation improves hrun plot_approx for td and observe fundamental problemregardless of sn not (there are ways to fix this issue filenameautofit_sines py exercise derive the trapezoidal rule for double integral use ideas in sect to derive formula for computing double integral rb rd xy/dydx by the trapezoidal rule implement and test this rule filenametrapezoidal_double py exercise compute the area of triangle by monte carlo integration use the monte carlo method from sect to compute the area of triangle with vertices at / /and filenamemc_triangle py
3,839
open access this is distributed under the terms of the creative commons attributionnoncommercial international license (which permits any noncommercial useduplicationadaptationdistribution and reproduction in any medium or formatas long as you give appropriate credit to the original author(sand the sourcea link is provided to the creative commons license and any changes made are indicated the images or other third party material in this are included in the work' creative commons licenseunless indicated otherwise in the credit lineif such material is not included in the work' creative commons license and the respective action is not permitted by statutory regulationusers will need to obtain permission from the license holder to duplicateadapt or reproduce the material
3,840
solving ordinary differential equations differential equations constitute one of the most powerful mathematical tools to understand and predict the behavior of dynamical systems in natureengineeringand society dynamical system is some system with some stateusually expressed by set of variablesthat evolves in time for examplean oscillating pendulumthe spreading of diseaseand the weather are examples of dynamical systems we can use basic laws of physicsor plain intuitionto express mathematical rules that govern the evolution of the system in time these rules take the form of differential equations you are probably well experienced with equationsat least equations like ax cb or ax cbx cc such equations are known as algebraic equationsand the unknown is number the unknown in differential equation is functionand differential equation will almost always involve this function and one or more derivatives of the function for examplef xd xis simple differential equation (asking if there is any function such that it equals its derivative you might remember that is candidatethe present starts with explaining how easy it is to solve both single (scalarfirst-order ordinary differential equations and systems of first-order differential equations by the forward euler method we demonstrate all the mathematical and programming details through two specific applicationspopulation growth and spreading of diseases then we turn to physical applicationoscillating mechanical systemswhich arise in wide range of engineering situations the differential equation is now of second orderand the forward euler method does not perform well this observa(cthe author( lingeh langtangenprogramming for computations pythontexts in computational science and engineering doi --
3,841
solving ordinary differential equations tion motivates the need for other solution methodsand we derive the euler-cromer scheme the ndand th-order runge-kutta schemesas well as finite difference scheme (the latter to handle the second-order differential equation directly without reformulating it as first-order systemthe presentation starts with undamped free oscillations and then treats general oscillatory systems with possibly nonlinear dampingnonlinear spring forcesand arbitrary external excitation besides developing programs from scratchwe also demonstrate how to access ready-made implementations of more advanced differential equation solvers in python as we progress with more advanced methodswe develop more sophisticated and reusable programsand in particularwe incorporate good testing strategies so that we bring solid evidence to correct computations consequentlythe beginning with population growth and disease modeling examples has very gentle learning curvewhile that curve gets significantly steeper towards the end of the treatment of differential equations for oscillatory systems population growth our first taste of differential equations regards modeling the growth of some populationsuch as cell culturean animal populationor human population the ideas even extend trivially to growth of money in bank let tbe the number of individuals in the population at time how can we predict the evolution of tin timebelow we shall derive differential equation whose solution is tthe equation reads td rn /( where is number note that although is an integer in real lifewe model as real-valued function we are forced to do this because the solution of differential equations are (normally continuousreal-valued functions an integer-valued tin the model would lead to lot of mathematical difficulties with bit of guessingyou may realize that td rt where is any number to make this solution uniquewe need to fix done by prescribing the value of at some timeusually say is given as then td rt in generala differential equation model consists of differential equationsuch as ( and an initial conditionsuch as with known initial conditionthe differential equation can be solved for the unknown function and the solution is unique it isof coursevery seldom that we can find the solution of differential equation as easy as in this example normallyone has to apply certain mathematical methodsbut these can only handle some of the simplest differential equations howeverwe can easily deal with almost any differential equation by applying numerical methods and bit of programming this is exactly the topic of the present the term scheme is used as synonym for method or computational recipeespecially in the context of numerical methods for differential equations
3,842
derivation of the model it can be instructive to show how an equation like ( arises consider some population of (sayan animal species and let tbe the number of individuals in certain spatial regione an island we are not concerned with the spatial distribution of the animalsjust the number of them in some spatial area where there is no exchange of individuals with other spatial areas during time interval tsome animals will die and some new will be born the number of deaths and births are expected to be proportional to for exampleif there are twice as many individualswe expect them to get twice as many newborns in time interval tthe net growth of the population will be td bn dn / where bn tis the number of newborns and dn tis the number of deaths if we double twe expect the proportionality constants bn and dn to double tooso it makes sense to think of bn and dn as proportional to and "factor outt that iswe introduce = and dn = to be proportionality constants for newborns and deaths independent of alsowe introduce which is the net rate of growth of the population per time unit our model then becomes td rn ( equation ( is actually computational model given /we can advance the population size by td tc rn tthis is called difference equation if we know tfor some te we can compute td rn td tc rn / td tc rn /: /td ktc rn kt/where is some arbitrary integer computer program can easily compute /tfor us with the aid of little loop warning observe that the computational formula cannot be started unless we have an initial conditionthe solution of rn is rt for any constant and the initial condition is needed to fix so the solution becomes unique howeverfrom mathematical point of viewknowing tat any point is sufficient as initial
3,843
solving ordinary differential equations condition numericallywe more literally need an initial conditionwe need to know starting value at the left end of the interval in order to get the computational formula going in factwe do not need computer since we see repetitive pattern when doing hand calculationswhich leads us to mathematical formula for / / /td ktc rn ktd kt rd / / : /kc rather than using ( as computational model directlythere is strong tradition for deriving differential equation from this difference equation the idea is to consider very small time interval and look at the instantaneous growth as this time interval is shrunk to an infinitesimally small size in mathematical termsit means that we let as ( standsletting will just produce an equation so we have to divide by and then take the limitn td rn tt ! lim the term on the left-hand side is actually the definition of the derivative /so we have td rn /which is the corresponding differential equation there is nothing in our derivation that forces the parameter to be constant it can change with time due toe seasonal changes or more permanent environmental changes detourexact mathematical solution if you have taken course on mathematical solution methods for differential equationsyou may want to recap how an equation like rn or / is solved the method of separation of variables is the most convenient solution strategy in this casen rn dn rn dt dn rdt zn zt dn rdt
3,844
zt ln ln /dt exp /dt which for constant results in rt note that exp tis the same as as will be described laterr must in more realistic models depend on the rn method of separation of variables then requires to integrate = /dn which quickly becomes non-trivial for many choices of the only generally applicable solution approach is therefore numerical method numerical solution there is huge collection of numerical methods for problems like ( )and in general any equation of the form ut/where tis the unknown function in the problemand is some known formula of and optionally for examplef utd ru in ( we will first present simple finite difference method solving utthe idea is four-fold introduce mesh in time with points tn we seek the unknown at the mesh points tn and introduce un as the numerical approximation to tn /see fig assume that the differential equation is valid at the mesh points approximate derivatives by finite differencessee fig formulate computational algorithm that can compute new value un based on previously computed values ui an example will illustrate the steps firstwe introduce the meshand very often the mesh is uniformmeaning that the spacing between points tn and tnc is constant this property implies that tn ntn secondthe differential equation is supposed to hold at the mesh points note that this is an approximationbecause the differential equation is originally valid at all real values of we can express this property mathematically as tn un tn / for examplewith our model equation ruwe have the special case tn run or tn tn /un if depends explicitly on
3,845
solving ordinary differential equations fig mesh in time with corresponding discrete values (unknownsfig illustration of forward difference approximation to the derivative thirdderivatives are to be replaced by finite differences to this endwe need to know specific formulas for how derivatives can be approximated by finite differences one simple possibility is to use the definition of the derivative from any calculus booku tu td lim ! at an arbitrary mesh point tn this definition can be written as unc un ! tn lim
3,846
instead of going to the limit we can use small twhich yields computable approximation to tn / tn unc un this is known as forward difference since we go forward in time (unc to collect information in to estimate the derivative figure illustrates the idea the error of the forward difference is proportional to (often written as /but we will not use this notation in the present bookwe can now plug in the forward difference in our differential equation sampled at the arbitrary mesh point tn unc un un tn / ( or with utd ru in our special model problem for population growthunc un run ( if depends on timewe insert tn for in this latter equation the fourth step is to derive computational algorithm looking at ( )we realize that if un should be knownwe can easily solve with respect to unc to get formula for at the next time level tnc unc un tf un tn ( provided we have known starting valueu we can use ( to advance the solution by first computing from then from from and so forth such an algorithm is called numerical scheme for the differential equation and often written compactly as unc un tf un tn / ( this scheme is known as the forward euler schemealso called euler' method in our special population growth modelwe have unc un run ( we may also write this model using the problem-specific symbol instead of the generic functionn nc rn nn ( the observant reader will realize that ( is nothing but the computational model ( arising directly in the model derivation the formula ( ariseshoweverfrom detour via differential equation and numerical method for the differential equation this looks rather unnecessarythe reason why we bother to
3,847
solving ordinary differential equations fig the numerical solution at points can be extended by linear segments between the mesh points derive the differential equation model and then discretize it by numerical method is simply that the discretization can be done in many waysand we can create (muchmore accurate and more computationally efficient methods than ( or ( this can be useful in many problemsneverthelessthe forward euler scheme is intuitive and widely applicableat least when is chosen to be small the numerical solution between the mesh points our numerical method computes the unknown function at discrete mesh points tn what if we want to evaluate the numerical solution between the mesh pointsthe most natural choice is to assume linear variation between the mesh pointssee fig this is compatible with the fact that when we plot the array versus : straight line is drawn between the discrete points programming the forward euler schemethe special case let us compute ( in program the input variables are trand note that we need to compute new values total of values are needed in an array representation of our first version of this program is as simple as possiblen_ input('give initial population size n_ ' input('give net growth rate 'dt input('give time step size'n_t input('give number of steps'from numpy import linspacezeros linspace( (n_t+ )*dtn_t+ zeros(n_t+
3,848
[ n_ for in range(n_t+ ) [ + [nr*dt* [nimport matplotlib pyplot as plt numerical_sol 'boif n_t else ' -plt plot(tnnumerical_soltn_ *exp( * )' -'plt legend(['numerical''exact']loc='upper left'plt xlabel(' ')plt ylabel(' ( )'filestem 'growth %dstepsn_t plt savefig('% pngfilestem)plt savefig('% pdffilestemthe complete code above resides in the file growth py let us demonstrate simulation where we start with animalsa net growth rate of percent ( per time unitwhich can be one monthand oe months we may first try of half month ( )which implies (or to be absolutely precisethe last time point to be computed according to our set-up above is tn : figure shows the results the solid line is the exact solutionwhile the circles are the computed numerical solution the discrepancy is clearly visible what if we make times smallerthe result is displayed in fig where we now use solid line also for the numerical solution (otherwise circles would look very clutteredso the program has test on how to display the numerical solutioneither as circles or solid linewe can hardly distinguish the exact and the numerical solution the computing time is also fraction of second on laptopso it appears that the forward euler method is sufficiently accurate for practical purposes (this is not always true for largecomplicated simulation models in engineeringso more sophisticated methods may be needed fig evolution of population computed with time step month
3,849
solving ordinary differential equations fig evolution of population computed with time step month it is also of interest to see what happens if we increase to months the results in fig indicate that this is an inaccurate computation fig evolution of population computed with time step months
3,850
understanding the forward euler method the good thing about the forward euler method is that it gives an understanding of what differential equation is and geometrical picture of how to construct the solution the first idea is that we have already computed the solution up to some time point tn the second idea is that we want to progress the solution from tn to tnc as straight line we know that the line must go through the solution at tn the point tn un the differential equation tells us the slope of the lineu tn un tn run that isthe differential equation gives direct formula for the further direction of the solution curve we can say that the differential equation expresses how the system (uundergoes changes at point there is general formula for straight line ax with slope that goes through the point / using this formula adapted to the present caseand evaluating the formula for tnc results in unc run tnc tn un un run which is nothing but the forward euler formula you are now encouraged to do exercise to become more familiar with the geometric interpretation of the forward euler method programming the forward euler schemethe general case our previous program was just flat main program tailored to special differential equation when programming mathematicsit is always good to consider (largeclass of problems and making python function to solve any problem that fits into the class more specificallywe will make software for the class of differential equation problems of the form td ut/ oe for some given function and numbers and we also take the opportunity to illustrate what is commonly called demo function as the name impliesthe purpose of such function is solely to demonstrate how the function works (not to be confused with test functionwhich does verification by use of assertthe python function calculating the solution must take tand as inputfind the corresponding compute the solutionand return an array with un and an array with tn the forward euler scheme reads unc un tf un tn / the corresponding program may now take the form (file ode_fe py)
3,851
solving ordinary differential equations from numpy import linspacezerosexp import matplotlib pyplot as plt def ode_fe(fu_ dtt)n_t int(round(float( )/dt) zeros(n_t+ linspace( n_t*dtlen( ) [ u_ for in range(n_t) [ + [ndt* ( [ ] [ ]return ut def demo_population_growth()"""test caseu'= *uu( )= ""def (ut)return * ut ode_fe( =fu_ = dt= = plt plot(tut *exp( * )plt show(if __name__ ='__main__'demo_population_growth(this program filecalled ode_fe pyis reusable piece of code with general ode_fe function that can solve any differential equation utand demo function for the special case : uu observe that the call to the demo function is placed in test block this implies that the call is not active if ode_fe is imported as module in another programbut active if ode_fe py is run as program the solution should be identical to what the growth py program produces with the same parameter settings ( : this feature can easily be tested by inserting print statementbut much betterautomated verification is suggested in exercise you are strongly encouraged to take "breakand do that exercise now remark on the use of as variable in the ode_fe programthe variable is used in different contexts inside the ode_fe functionu is an arraybut in the ( ,tfunctionas exemplified in the demo_population_growth functionthe argument is number typicallywe call (in ode_fewith the argument as one element of the array in the ode_fe functionu[nmaking the population growth model more realistic exponential growth of population according the model rn with exponential solution rt is unrealistic in the long run because the resources needed to feed the population are finite at some point there will not be enough resources and the growth will decline common model taking this effect into account as
3,852
sumes that depends on the size of the populationn td // tthe corresponding differential equation becomes / the reader is strongly encouraged to repeat the steps in the derivation of the forward euler scheme and establish that we get nc / which computes as easy as for constant rsince nis known when computing nc alternativelyone can use the forward euler formula for the general problem utand use utd / and replace by the simplest choice of is linear functionstarting with some growth value rn and declining until the population has reached its maximumm according to the available resourcesr rn = in the beginningn and we will have exponential growth rtn but as increasesr decreasesand when reaches so there is now more growth and the population remains at td this linear choice of gives rise to model that is called the logistic model the parameter is known as the carrying capacity of the population let us run the logistic model with aid of the ode_fe function in the ode_fe module we choose : montht monthsr : and the complete programcalled logistic pyis basically call to ode_fefrom ode_fe import ode_fe import matplotlib pyplot as plt for dtt in zip(( )( ))ut ode_fe( =lambda ut *( / )*uu_ = dt=dtt=tplt figure(make separate figures for each pass in the loop plt plot(tu' -'plt xlabel(' ')plt ylabel(' ( )'plt savefig('tmp_% pngdt)plt savefig('tmp_% pdfdtfigure shows the resulting curve we see that the population stabilizes around individuals corresponding exponential growth would reach rt :  ; individualsit is always interesting to see what happens with large values we may set and now the solutionseen in fig oscillates and is hence qualitatively wrongbecause one can prove that the exact solution of the differential equation is monotone (howeverthere is corresponding difference
3,853
solving ordinary differential equations fig logistic growth of population fig logistic growth with large time step equation modelnnc rnn nn = /which allows oscillatory solutions and those are observed in animal populations the problem with large is that it just leads to wrong mathematics and two wrongs don' make right in terms of relevant model
3,854
remark on the world population the number of people on the planet follows the model / where the net reproduction tvaries with time and has decreased since its top in the current world value of is %and it is difficult to predict future values at the momentthe predictions of the world population point to growth to billion before declining this example shows the limitation of differential equation modelwe need to know all input parametersincluding /in order to predict the future it is seldom the case that we know all input parameters sometimes knowledge of the solution from measurements can help estimate missing input parameters verificationexact linear solution of the discrete equations how can we verify that the programming of an ode model is correctthe best method is to find problem where there are no unknown numerical approximation errorsbecause we can then compare the exact solution of the problem with the result produced by our implementation and expect the difference to be within very small tolerance we shall base unit test on this idea and implement corresponding test function (see sect for automatic verification of our implementation it appears that most numerical methods for odes will exactly reproduce solution that is linear in we may therefore set at and choose any whose derivative is the choice utd is very simplebut we may add anything that is zeroe utd at // this is valid utfor any aband the corresponding ode looks highly non-trivialhoweveru at // using the general ode_fe function in ode_fe pywe may write proper test function as follows (in file test_ode_fe_exact_linear py)def test_ode_fe()"""test that linear ( )= * + is exactly reproduced ""def exact_solution( )return * def (ut)ode return ( exact_solution( ))** -
3,855
solving ordinary differential equations dt ut ode_fe(fexact_solution( )dttdiff abs(exact_solution(tumax(tol - tolerance for float comparison success diff tol assert success recall that test functions should start with the name test_have no argumentsand formulate the test as boolean expression success that is true if the test passes and false if it fails test functions should make the test as assert success (here success can also be boolean expression as in assert diff tolobserve that we cannot compare diff to zerowhich is what we mathematically expectbecause diff is floating-point variable that most likely contains small rounding errors thereforewe must compare diff to zero with tolerancehere you are encouraged to do exercise where the goal is to make test function for verification based on comparison with hand-calculated results for few time steps spreading of diseases our aim with this section is to show in detail how one can apply mathematics and programming to investigate spreading of diseases the mathematical model is now system of three differential equations with three unknown functions to derive such modelwe can use mainly intuitionso no specific background knowledge of diseases is required spreading of flu imagine boarding school out in the country side this school is small and closed society suddenlyone or more of the pupils get flu we expect that the flu may spread quite effectively or die out the question is how many of the pupils and the school' staff will be affected some quite simple mathematics can help us to achieve insight into the dynamics of how the disease spreads let the mathematical function tcount how many individualsat time tthat have the possibility to get infected heret may count hours or daysfor instance these individuals make up category called susceptibleslabeled as another categoryiconsists of the individuals that are infected let tcount how many there are in category at time an individual having recovered from the disease is assumed to gain immunity there is also small possibility that an infected will die in either casethe individual is moved from the category to category we call the removed categorylabeled with we let tcount the number of individuals in the category at time those who enter the categorycannot leave this category
3,856
to summarizethe spreading of this disease is essentially the dynamics of moving individuals from the to the and then to the categorywe can use mathematics to more precisely describe the exchange between the categories the fundamental idea is to describe the changes that take place during small time intervaldenoted by our disease model is often referred to as compartment modelwhere quantities are shuffled between compartments (here synonym for categoriesaccording to some rules the rules express changes in small time interval tand from these changes we can let go to zero and obtain derivatives the resulting equations then go from difference equations (with finite tto differential equations ( we introduce uniform mesh in timetn ntn and seek at the mesh points the numerical approximation to at time tn is denoted by similarlywe seek the unknown values of tand tat the mesh points and introduce similar notation and rn for the approximations to the exact values tn and tn in the time interval we know that some people will be infectedso will decrease we shall soon argue by mathematics that there will be vtsi new infected individuals in this time intervalwhere is parameter reflecting how easy people get infected during time interval of unit length if the loss in is vtsi we have that the change in is nc vts ( dividing by and letting makes the left-hand side approach tn such that we obtain differential equation vsi ( the reasoning in going from the difference equation ( to the differential equation ( follows exactly the steps explained in sect before proceeding with how and develops in timelet us explain the formula vtsi we have susceptibles and infected people these can make up si pairs nowsuppose that during time interval we measure that actual pairwise meetings do occur among theoretically possible pairings of people from the and categories the probability that people meet in pairs during time is (by the empirical frequency definition of probabilityequal to =ni the number of successes divided by the number of possible outcomes from such statistics we normally derive quantities expressed per unit timei here we want the probability per unit timewhich is found from dividing by mnt given the probability the expected number of meetings per time interval of si possible pairs of people is (from basic statisticssi during time interval tthere will be sit expected number of meetings between susceptibles and infected people such that the virus may spread only fraction of the tsi
3,857
solving ordinary differential equations meetings are effective in the sense that the susceptible actually becomes infected counting that people get infected in such pairwise meetings (say are infected from meetings)we can estimate the probability of being infected as = the expected number of individuals in the category that in time interval catch the virus and get infected is then tsi introducing new constant pto save some writingwe arrive at the formula vtsi the value of must be known in order to predict the future with the disease model one possibility is to estimate and from their meanings in the derivation above alternativelywe can observe an "experimentwhere there are susceptibles and infected at some point in time during time interval we count that susceptibles have become infected using ( as rough approximation of how has developed during time (and now is not necessarily smallbut we use ( anyway)we get ( vt we need an additional equation to describe the evolution of tsuch an equation is easy to establish by noting that the loss in the category is corresponding gain in the category more preciselyi nc vts ( howeverthere is also loss in the category because people recover from the disease suppose that we can measure that out of individuals recover in time period (say of sick people recover during daym hnowd mnt is the probability that one individual recovers in unit time interval then (on averageti infected will recover in time interval this quantity represents loss in the category and gain in the category we can therefore write the total change in the category as nc vts ti ( the change in the category is simplethere is always an increase from the categoryrnc rn ti ( since there is no loss in the category (people are either recovered and immuneor dead)we are done with the modeling of this category in factwe do not strictly need the equation ( for rbut extensions of the model later will need an equation for dividing by in ( and ( and letting results in the corresponding differential equations and vsi ( ( to summarizewe have derived difference equations ( )-( )and alternative differential equations ( )-( for referencewe list the complete set of the
3,858
three difference equationss nc vts ( nc vts ti ( nc ti ( note that we have isolated the new unknown quantities nc nc and rnc on the left-hand sidesuch that these can readily be computed if and rn are known to get such procedure startedwe need to know obviouslywe also need to have values for the parameters and we also list the system of three differential equationss vsii vsi ir ( ( ( this differential equation model (and also its discrete counterpart aboveis known as an sir model the input data to the differential equation model consist of the parameters and as well as the initial conditions and forward euler method for the differential equation system let us apply the same principles as we did in sect to discretize the differential equation system by the forward euler method we already have time mesh and time-discrete quantities rn the three differential equations are assumed to be valid at the mesh points at the point tn we then have tn vs tn / tn / tn vs tn / tn tn / tn tn /( ( ( for this is an approximation since the differential equations are originally valid at all times (usually in some finite interval oe using forward finite differences for the derivatives results in an additional approximations nc vs nc vs rnc rn in ( ( ( as we seethese equations are identical to the difference equations that naturally arise in the derivation of the model howeverother numerical methods than the forward euler scheme will result in slightly different difference equations
3,859
solving ordinary differential equations programming the numerical methodthe special case the computation of ( )-( can be readily made in computer program sir pyfrom numpy import zeroslinspace import matplotlib pyplot as plt time unit beta /( * * gamma /( * dt min simulate for days n_t int( * /dtcorresponding no of hours linspace( n_t*dtn_t+ zeros(n_t+ zeros(n_t+ zeros(n_t+ initial condition [ [ [ step equations forward in time for in range(n_t) [ + [ndt*beta* [ ]* [ni[ + [ndt*beta* [ ]* [ndt*gamma* [nr[ + [ndt*gamma* [nfig plt figure( plt plot(tstitrfig legend(( )(' '' '' ')'upper left'plt xlabel('hours'plt show(plt savefig('tmp pdf')plt savefig('tmp png'this program was written to investigate the spreading of flu at the mentioned boarding schooland the reasoning for the specific choices and goes as follows at some other school where the disease has already spreadit was observed that in the beginning of day there were susceptibles and infectedwhile the numbers were and respectively hours later using as time unitwe then have from ( that among infectedit was observed that recovered during daygiving applying these parameters to new case where there is one infected initially and susceptiblesgives the graphs in fig these graphs are just straight lines between the values at times ti it as computed by the program we observe that reduces as and grows after about days everyone has become ill and recovered again we can experiment with and to see whether we get an outbreak of the disease or not imagine that "wash your handscampaign was successful and that the other school in this case experienced reduction of by factor of with this
3,860
fig natural evolution of flu at boarding school lower the disease spreads very slowly so we simulate for days the curves appear in fig fig small outbreak of flu at boarding school ( is much smaller than in fig
3,861
solving ordinary differential equations outbreak or not looking at the equation for it is clear that we must have vsi for to increase when we start the simulation it means that vs / or simpler vs > ( to increase the number of infected people and accelerate the spreading of the disease you can run the sir py program with smaller such that ( is violated and observe that there is no outbreak the power of mathematical modeling the reader should notice our careful use of words in the previous paragraphs we started out with modeling very specific casenamely the spreading of flu among pupils and staff at boarding school with purpose we exchanged words like pupils and flu with more neutral and general words like individuals and diseaserespectively phrased equivalentlywe raised the abstraction level by moving from specific case (flu at boarding schoolto more general case (disease in closed societyvery oftenwhen developing mathematical modelswe start with specific example and seethrough the modelingthat what is going on of essence in this example also will take place in many similar problem settings we try to incorporate this generalization in the model so that the model has much wider application area than what we aimed at in the beginning this is the very power of mathematical modelingby solving one specific case we have often developed more generic tools that can readily be applied to solve seemingly different problems the next sections will give substance to this assertion abstract problem and notation when we had specific differential equation with one unknownwe quickly turned to an abstract differential equation written in the generic form utwe refer to such problem as scalar ode specific equation corresponds to specific choice of the formula utinvolving and (optionallyt it is advantageous to also write system of differential equations in the same abstract notationu ut/but this time it is understood that is vector of functions and is also vector we say that utis vector ode or system of odes in this case for the sir model we introduce the two -vectorsone for the unknownsu / / //
3,862
and one for the right-hand side functionsf utd vsivsi ii the equation utmeans setting the two vectors equali the components must be pairwise equal since /we get that implies vsii vsi ir the generalized short notation utis very handy since we can derive numerical methods and implement software for this abstract system and in particular application just identify the formulas in the vectorimplement theseand call functionality that solves the differential equation system programming the numerical methodthe general case in python codethe forward euler step unc un tf un tn /being scalar or vector equationcan be coded as [ + [ndt* ( [ ] [ ]both in the scalar and vector case in the vector caseu[nis one-dimensional numpy array of length holding the mathematical quantity un and the python function must return numpy array of length then the expression [ndt* ( [ ] [ ]is an array plus scalar times an array for all this to workthe complete numerical solution must be represented by two-dimensional arraycreated by zeros((n_t+ + )the first index counts the time points and the second the components of the solution vector at one time point that isu[ ,icorresponds to the mathematical quantity uni when we use only one indexas in [ ]this is the same as [ ,:and picks out all the components in the solution at the time point with index then the assignment [ + becomes correct because it is actually an in-place assignment [ + :the nice feature of these facts is that the same piece of python code works for both scalar ode and system of odesthe ode_fe function for the vector ode is placed in the file ode_system_fe py and was written as followsfrom numpy import linspacezerosasarray import matplotlib pyplot as plt def ode_fe(fu_ dtt)n_t int(round(float( )/dt)
3,863
solving ordinary differential equations ensure that any list/tuple returned from f_ is wrapped as array f_ lambda utasarray( (ut) zeros((n_t+ len(u_ )) linspace( n_t*dtlen( ) [ u_ for in range(n_t) [ + [ndt*f_( [ ] [ ]return ut the line f_ lambda needs an explanation for userwho just needs to define the in the ode systemit is convenient to insert the various mathematical expressions on the right-hand sides in list and return that list obviouslywe could demand the user to convert the list to numpy arraybut it is so easy to do general such conversion in the ode_fe function as well to make sure that the result from is indeed an array that can be used for array computing in the formula [ndt* ( [ ] [ ])we introduce new function f_ that calls the user' and sends the results through the numpy function asarraywhich ensures that its argument is converted to numpy array (if it is not already an arraynote also the extra parenthesis required when calling zeros with two indices let us show how the previous sir model can be solved using the new general ode_fe that can solve any vector ode the user' (utfunction takes vector uwith three components corresponding to si and as argumentalong with the current time point [ ]and must return the values of the formulas of the right-hand sides in the vector ode an appropriate implementation is def (ut)sir return [-beta* *ibeta* * gamma*igamma*inote that the siand values correspond to and rn these values are then just inserted in the various formulas in the vector ode here we collect the values in list since the ode_fe function will anyway wrap this list in an array we couldof coursereturned an array insteaddef (ut)sir return array([-beta* *ibeta* * gamma*igamma* ]the list version looks bit nicerso that is why we prefer list and rather introduce f_ lambda utasarray( ( , )in the general ode_fe function we can now show function that runs the previous sir examplewhile using the generic ode_fe functiondef demo_sir()"""test case using sir model ""def (ut)sir return [-beta* *ibeta* * gamma*igamma*
3,864
beta /( * * gamma /( * dt min simulate for days n_t int( * /dtcorresponding no of hours dt*n_t end time u_ [ ut ode_fe(fu_ dtts [:, [:, [:, fig plt figure( plt plot(tstitrfig legend(( )(' '' '' ')'lower right'plt xlabel('hours'plt show(consistency checkn [ [ [ eps - tolerance for comparing real numbers for in range(len( ))sir_sum [ni[nr[nif abs(sir_sum nepsprint '**consistency check faileds+ + =% !% %(sir_sumnif __name__ ='__main__'demo_sir(recall that the returned from ode_fe contains all components (si rin the solution vector at all time points we therefore need to extract the si and values in separate arrays for further analysis and easy plotting another key feature of this higher-quality code is the consistency check by adding the three differential equations in the sir modelwe realize that which means that ci cr const we can check that this relation holds by comparing rn to the sum of the initial conditions the check is not full-fledged verificationbut it is much better than doing nothing and hoping that the computation is correct exercise suggests another method for controlling the quality of the numerical solution time-restricted immunity let us now assume that immunity after the disease only lasts for some certain time period this means that there is transport from the state to the state
3,865
solving ordinary differential equations modeling the loss of immunity is very similar to modeling recovery from the diseasethe amount of people losing immunity is proportional to the amount of recovered patients and the length of the time interval we can therefore write the loss in the category as tr in time twhere is the typical time it takes to lose immunity the loss in tis gain in tthe "budgetsfor the categories therefore become nc vts trn ( nc vts ti ( nc ti tr ( dividing by and letting gives the differential equation system vsi ri vsi ir ( ( ( this system can be solved by the same methods as we demonstrated for the original sir model only one modification in the program is necessaryadding nu* [nto the [ + update and subtracting the same quantity in the [ + updatefor in range(n_t) [ + [ndt*beta* [ ]* [ndt*nu* [ni[ + [ndt*beta* [ ]* [ndt*gamma* [nr[ + [ndt*gamma* [ndt*nu* [nthe modified code is found in the file sir py setting to daysreducing by factor of compared to the previous example ( : )and simulating for days gives an oscillatory behavior in the categoriesas depicted in fig it is easy now to play around and study how the parameters affect the spreading of the disease for examplemaking the disease slightly more effective (increase to and increasing the average time to loss of immunity to days lead to other oscillationssee fig incorporating vaccination we can extend the model to also include vaccination to this endit can be useful to track those who are vaccinated and those who are not sowe introduce fourth categoryvfor those who have taken successful vaccination furthermorewe assume that in time interval ta fraction pt of the category is subject to successful vaccination this means that in the time tpts people leave from the to the category since the vaccinated ones cannot get the diseasethere is no impact on the or categories we can visualize the categoriesand the movement between themas
3,866
fig including loss of immunity fig increasing and reducing compared to fig
3,867
solving ordinary differential equations the newextended differential equations with the quantity become vsi psv psi vsi ir ( ( ( ( we shall refer to this model as the sirv model the new equation for poses no difficulties when it comes to the numerical method in forward euler scheme we simply add an update nc pts the program needs to store tin an additional array vand the plotting command must be extended with more arguments to plot versus as well the complete code is found in the file sirv py using : and : as values for the vaccine efficiency parameterthe effect of vaccination is seen in fig (other parameters are as in fig fig the effect of vaccinationp : (leftand : (right
3,868
discontinuous coefficientsa vaccination campaign what about modeling vaccination campaignimagine that six days after the outbreak of the diseasethe local health station launches vaccination campaign they reach out to many peoplesay times as efficiently as in the previous (constant vaccinationcase if the campaign lasts for days we can write td : otherwise note that we must multiply the value by because is measured in hoursnot days in the differential equation systemps tmust be replaced by / /and in this case we get differential equation system with term that is discontinuous this is usually quite challenge in mathematicsbut as long as we solve the equations numerically in programa discontinuous coefficient is easy to treat there are two ways to implement the discontinuous coefficient /through function and through an array the function approach is perhaps the easiestdef ( )return if ( * < < * else in the code for updating the arrays and we get term ( [ ])* [nwe can also let tbe an array filled with correct values prior to the simulation then we need to allocate an array of length n_t+ and find the indices corresponding to the time period between and days these indices are found from the time point divided by that isp zeros(n_t+ start_index * /dt stop_index * /dt [start_index:stop_index the / tterm in the updating formulas for and simply becomes [ ]* [nthe file sirv py contains program based on filling an array the effect of vaccination campaign is illustrated in fig all the data are as in fig (left)except that is ten times stronger for period of days and elsewhere
3,869
solving ordinary differential equations fig the effect of vaccination campaign oscillating one-dimensional systems numerous engineering constructions and devices contain materials that act like springs such springs give rise to oscillationsand controlling oscillations is key engineering task we shall now learn to simulate oscillating systems as alwayswe start with the simplest meaningful mathematical modelwhich for oscillations is second-order differential equationu tc td ( where is given physical parameter equation ( models one-dimensional system oscillating without damping ( with negligible dampingone-dimensional here means that some motion takes place along one dimension only in some coordinate system along with ( we need the two initial conditions and derivation of simple model many engineering systems undergo oscillationsand differential equations constitute the key tool to understandpredictand control the oscillations we start with the simplest possible model that captures the essential dynamics of an oscillating system some body with mass is attached to spring and moves along line without frictionsee fig for sketch (rolling wheels indicate "no friction"when the spring is stretched (or compressed)the spring force pulls (or pushesthe body back and work "againstthe motion more preciselylet tbe the position
3,870
fig sketch of one-dimensionaloscillating dynamic system (without frictionof the body on the axisalong which the body moves the spring is not stretched when so the force is zeroand is hence the equilibrium position of the body the spring force is kxwhere is constant to be measured we assume that there are no other forces ( no frictionnewton' nd law of motion ma then has kx and xr kx mxr ( which can be rewritten as xr ( by introducing = (which is very commonequation ( is second-order differential equationand therefore we need two initial conditionsone on the position and one on the velocity here we choose the body to be at restbut moved away from its equilibrium positionx the exact solution of ( with these initial conditions is td cos ! this can easily be verified by substituting into ( and checking the initial conditions the solution tells that such spring-mass system oscillates back and forth as described by cosine curve the differential equation ( appears in numerous other contexts classical example is simple pendulum that oscillates back and forth physics books derivefrom newton' second law of motionthat ml mg sin where is the mass of the body at the end of pendulum with length lg is the acceleration of gravityand is the angle the pendulum makes with the vertical considering small angles sin and we get ( with  =lx and if is the initial angle and the pendulum is at rest at
3,871
solving ordinary differential equations numerical solution we have not looked at numerical methods for handling second-order derivativesand such methods are an optionbut we know how to solve first-order differential equations and even systems of first-order equations with littleyet very commontrick we can rewrite ( as first-order system of two differential equations we introduce and as two new unknown functions the two corresponding equations arise from the definition and the original equation ( ) ( ( (notice that we can use to remove the second-order derivative from newton' nd law we can now apply the forward euler method to ( )-( )exactly as we did in sect unc un vn nc un ( ( resulting in the computational scheme unc un nc programming the numerical methodthe special case simple program for ( )-( follows the same ideas as in sect from numpy import zeroslinspacepicosarray import matplotlib pyplot as plt omega *pi/omega dt / * n_t int(round( /dt) linspace( n_t*dtn_t+ zeros(n_t+ zeros(n_t+ initial condition x_ [ x_ [ ( (
3,872
step equations forward in time for in range(n_t) [ + [ndt* [nv[ + [ndt*omega** * [nfig plt figure( plt plot(tu' -'tx_ *cos(omega* )' --'fig legend(( )('numerical''exact')'upper left'plt xlabel(' 'plt show(plt savefig('tmp pdf')plt savefig('tmp png'(see file osc_fe py since we already know the exact solution as td cos !twe have reasoned as follows to find an appropriate simulation interval oe and also how many points we should choose the solution has period =(the period is the time difference between two peaks of the tcos ! curve simulating for three periods of the cosine functiont and choosing such that there are intervals per period gives = and total of = intervals the rest of the program is straightforward coding of the forward euler scheme figure shows comparison between the numerical solution and the exact solution of the differential equation to our surprisethe numerical solution looks wrong is this discrepancy due to programming error or problem with the forward euler methodfirst of alleven before trying to run the programyou should sit down and compute two steps in the time loop with calculator so you have some intermediate results to compare with using dt : and we fig simulation of an oscillating system
3,873
solving ordinary differential equations get : : and : such calculations show that the program is seemingly correct (laterwe can use such values to construct unit test and corresponding test function the next step is to reduce the discretization parameter and see if the results become more accurate figure shows the numerical and exact solution for the cases = = = the results clearly become betterand the finest resolution gives graphs that cannot be visually distinguished neverthelessthe finest resolution involves computational intervals in totalwhich is considered quite much this is no problem on modern laptophoweveras the computations take just fraction of second although intervals per oscillation period seem sufficient for an accurate numerical solutionthe lower right graph in fig shows that if we increase the simulation timehere to periodsthere is little growth of the amplitudewhich becomes significant over time the conclusion is that the forward euler method has fundamental problem with its growing amplitudesand that very small is required to achieve satisfactory results the longer the simulation isthe smaller has to be it is certainly time to look for more effective numerical methodsfig simulation of an oscillating system with different time steps upper left steps per oscillation period upper right steps per period lower left steps per period lower right steps per periodbut longer simulation
3,874
magic fix of the numerical method in the forward euler schemeunc un nc un we can replace un in the last equation by the recently computed value unc from the first equationunc un nc nc ( ( before justifying this fix more mathematicallylet us try it on the previous example the results appear in fig we see that the amplitude does not growbut the phase is not entirely correct after periods (fig rightwe see significant difference between the numerical and the exact solution decreasing decreases the error for examplewith intervals per periodwe only see small phase error even after , periods (!we can safely conclude that the fix results in an excellent numerical methodlet us interpret the adjusted scheme mathematically first we order ( )-( such that the difference approximations to derivatives become transparentunc un vn nc unc ( ( we interpret ( as the differential equation sampled at mesh point tn because we have on the right-hand side the left-hand side is then forward difference or forward euler approximation to the derivative see fig on the other handwe interpret ( as the differential equation sampled at mesh point tnc since we fig adjusted methodfirst three periods (leftand period - (right
3,875
solving ordinary differential equations have unc on the right-hand side in this casethe difference approximation on the left-hand side is backward differencev tnc nc or tn figure illustrates the backward difference the error in the backward difference is proportional to tthe same as for the forward difference (but the proportionality constant in the error term has different signthe resulting discretization method for ( is often referred to as backward euler scheme to summarizeusing forward difference for the first equation and backward difference for the second equation results in much better method than just using forward differences in both equations the standard way of expressing this scheme in physics is to change the order of the equationsv uu ( ( and apply forward difference to ( and backward difference to ( ) nc un ( ( nc nc that isfirst the velocity is updated and then the position uusing the most recently computed velocity there is no difference between ( )-( and ( )( with respect to accuracyso the order of the original differential equations does not matter the scheme ( )-( goes under the names semi-implicit euler or euler-cromer the implementation of ( )-( is found in the file osc_ec py the core of the code goes like fig illustration of backward difference approximation to the derivative
3,876
zeros(n_t+ zeros(n_t+ initial condition [ [ step equations forward in time for in range(n_t) [ + [ndt*omega** * [nu[ + [ndt* [ + the nd-order runge-kutta method (or heun' methoda very popular method for solving scalar and vector odes of first order is the nd-order runge-kutta method (rk )also known as heun' method the ideafirst thinking of scalar odeis to form centered difference approximation to the derivative between two time points unc un tn the centered difference formula is visualized in fig the error in the centered difference is proportional to one order higher than the forward and backward differenceswhich means that if we halve tthe error is more effectively reduced in the centered difference since it is reduced by factor of four rather than two the problem with such centered scheme for the general ode utis that we get unc un unc tnc / which leads to difficulties since we do not know what unc is howeverwe can approximate the value of between two time levels by the arithmetic average of fig illustration of centered difference approximation to the derivative
3,877
solving ordinary differential equations the values at tn and tnc unc tnc un tn unc tnc / this results in unc un un tn unc tnc // which in general is nonlinear algebraic equation for unc if utis not linear function of to deal with the unknown term unc tnc /without solving nonlinear equationswe can approximate or predict unc using forward euler stepunc un tf un tn this reasoning gives rise to the method un tf un tn / un tn tnc /unc un ( ( the scheme applies to both scalar and vector odes for an oscillating system with uthe file osc_heun py implements this method the demo function in that file runs the simulation for periods with time steps per period the corresponding numerical and exact solutions are shown in fig we see that the amplitude growsbut not as much as for the forward euler method howeverthe euler-cromer method is much betterwe should add that in problems where the forward euler method gives satisfactory approximationssuch as growth/decay problems or the sir modelthe nd-order runge-kutta method or heun' methodusually works considerably better and produces greater accuracy for the same computational cost it is therefore very valuable method to be aware ofalthough it cannot compete with the eulercromer scheme for oscillation problems the derivation of the rk /heun scheme is also good general training in "numerical thinkingsoftware for solving odes there is jungle of methods for solving odesand it would be nice to have easy access to implementations of wide range of methodsespecially the sophisticated and complicated adaptive methods that adjust automatically to obtain prescribed accuracy the python package odespy gives easy access to lot of numerical methods for odes the simplest possible example on using odespy is to solve uu for time steps until
3,878
fig simulation of periods of oscillations by heun' method import odespy def (ut)return method odespy heun ore odespy forwardeuler solver method(fsolver set_initial_condition( time_points np linspace( ut solver solve(time_pointsin other wordsyou define your right-hand side function (ut)initialize an odespy solver objectset the initial conditioncompute collection of time points where you want the solutionand ask for the solution the returned arrays and can be plotted directlyplot(tua nice feature of odespy is that problem parameters can be arguments to the user' (utfunction for exampleif our ode problem is au bwith two problem parameters and bwe may write our function as def (utab)return - * the extraproblem-dependent arguments and can be transferred to this function if we collect their values in list or tuple when creating the odespy solver and use the f_args argument
3,879
solving ordinary differential equations solver method(ff_args=[ab]this is good feature because problem parameters must otherwise be global variables now they can be arguments in our right-hand side function in natural way exercise asks you to make complete implementation of this problem and plot the solution using odespy to solve oscillation odes like reformulated as system and uis done as follows we specify given number of time steps per period and compute the associated time steps and end time of the simulation ( )given number of periods to simulateimport odespy define the ode system uv -omega** * def (soltomega= )uv sol return [ -omega** *uset and compute problem dependent parameters omega x_ number_of_periods time_intervals_per_period from numpy import pilinspacecos *pi/omega length of one period dt /time_intervals_per_period time step number_of_periods* final simulation time create odespy solver object odespy_method odespy rk solver odespy_method(ff_args=[omega]the initial condition for the system is collected in list solver set_initial_condition([x_ ]compute the desired time points where we want the solution n_t int(round( /dt)no of time intervals time_points linspace( tn_t+ solve the ode problem solt solver solve(time_pointsnotesol contains both displacement and velocity extract original variables sol[:, sol[:, the last two statements are important since our two functions and in the ode system are packed together in one array inside the odespy solver the solution
3,880
of the ode system is returned as two-dimensional array where the first column (sol[:, ]stores and the second (sol[:, ]stores plotting and is matter of running plot(tutvremark in the right-hand side function we write (soltomegainstead of (utomegato indicate that the solution sent to is solution at time where the values of and are packed togethersol [uvwe might well use as argumentdef (utomega= )uv return [ -omega** *uthis just means that we redefine the name inside the function to mean the solution at time for the first component of the ode system to switch to another numerical methodjust substitute rk by the proper name of the desired method typing pydoc odespy in the terminal window brings up list of all the implemented methods this very simple way of choosing method suggests an obvious extension of the code abovewe can define list of methodsrun all methodsand compare their curves in plot as odespy also contains the euler-cromer schemewe rewrite the system with as the first ode and as the second odebecause this is the standard choice when using the euler-cromer method (also in odespy)def (utomega= )vu return [-omega** *uvthis change of equations also affects the initial conditionthe first component is zero and second is x_ so we need to pass the list [ x_ to solver set_ initial_condition the code osc_odespy py contains the detailsdef compare(odespy_methodsomegax_ number_of_periodstime_intervals_per_period= )from numpy import pilinspacecos *pi/omega length of one period dt /time_intervals_per_period number_of_periods*
3,881
solving ordinary differential equations if odespy_methods is not listbut just the name of single odespy solverwe wrap that name in list so we always have odespy_methods as list if type(odespy_methods!type([])odespy_methods [odespy_methodsmake list of solver objects solvers [method(ff_args=[omega]for method in odespy_methodsfor solver in solverssolver set_initial_condition([ x_ ]compute the time points where we want the solution dt float(dtavoid integer division n_t int(round( /dt)time_points linspace( n_t*dtn_t+ legends [for solver in solverssolt solver solve(time_pointsv sol[:, sol[:, plot only the last periods *time_intervals_per_period no time steps to plot plot( [- :] [- :]hold('on'legends append(solver name()xlabel(' 'plot exact solution too plot( [- :]x_ *cos(omega* )[- :]' --'legends append('exact'legend(legendsloc='lower left'axis([ [- ] [- ]- *x_ *x_ ]title('simulation of % periods with % intervals per period(number_of_periodstime_intervals_per_period)savefig('tmp pdf')savefig('tmp png'show( new feature in this code is the ability to plot only the last periodswhich allows us to perform long time simulations and watch the end results without cluttered plot with too many periods the syntax [- :plots the last elements in ( negative index in python arrays/lists counts from the endwe may compare heun' method (or equivalently the rk methodwith the euler-cromer schemecompare(odespy_methods=[odespy heunodespy eulercromer]omega= x_ = number_of_periods= time_intervals_per_period= figure shows how heun' method (the blue line with small diskshas considerable error in both amplitude and phase already after - periods (upper left)but using three times as many time steps makes the curves almost equal (upper
3,882
fig illustration of the impact of resolution (time steps per periodand length of simulation righthoweverafter - periods the errors have grown (lower left)but can be sufficiently reduced by halving the time step (lower rightwith all the methods in odespy at handit is now easy to start exploring other methodssuch as backward differences instead of the forward differences used in the forward euler scheme exercise addresses that problem odespy contains quite sophisticated adaptive methods where the user is "guaranteedto get solution with prescribed accuracy there is no mathematical guaranteebut the error will for most cases not deviate significantly from the user' tolerance that reflects the accuracy very popular method of this type is the runge-kutta-fehlberg methodwhich runs th-order runge-kutta method and uses th-order runge-kutta method to estimate the error so that can be adjusted to keep the error below tolerance this method is also widely known as ode because that is the name of the function implementing the method in matlab we can easily test the runge-kutta-fehlberg method as soon as we know the corresponding odespy namewhich is rkfehlbergcompare(odespy_methods=[odespy eulercromerodespy rkfehlberg]omega= x_ = number_of_periods= time_intervals_per_period=
3,883
solving ordinary differential equations fig comparison of the runge-kutta-fehlberg adaptive method against the euler-cromer scheme for long time simulation ( periodsnote that the time_intervals_per_period argument refers to the time points where we want the solution these points are also the ones used for numerical computations in the odespy eulercromer solverwhile the odespy rkfehlberg solver will use an unknown set of time points since the time intervals are adjusted as the method runs one can easily look at the points actually used by the method as these are available as an array solver t_all (but plotting or examining the points requires modifications inside the compare methodfigure shows computational example where the runge-kutta-fehlberg method is clearly superior to the euler-cromer scheme in long time simulationsbut the comparison is not really fair because the runge-kutta-fehlberg method applies about twice as many time steps in this computation and performs much more work per time step it is quite complicated task to compare two so different methods in fair way so that the computational work versus accuracy is scientifically well reported the th-order runge-kutta method the th-order runge-kutta method (rk is clearly the most widely used method to solve odes its power comes from high accuracy even with not so small time steps
3,884
fig the last of periods of oscillations by the th-order runge-kutta method the algorithm we first just state the four-stage algorithmunc un fonc fqnc fnnc ( where tnc nc nc tnc fnnc un fqnc tnc fonc ( ( ( application we can run the same simulation as in figs and for periods the last periods are shown in fig the results look as impressive as those of the euler-cromer method implementation the stages in the th-order runge-kutta method can easily be implemented as modification of the osc_heun py code alternativelyone can use the osc_odespy py code by just providing the argument odespy_methods[odespy rk to the compare function derivation the derivation of the th-order runge-kutta method can be presented in pedagogical way that brings many fundamental elements of numerical discretization techniques together and that illustrates many aspects of "numerical thinkingwhen constructing approximate solution methods
3,885
solving ordinary differential equations we start with integrating the general ode utover time stepfrom tn to tnc ztnc / /dt tnc tn tn nc the goal of the computation is tnc ( )while tn (un is the most recently known value of the challenge with the integral is that the integrand involves the unknown between tn and tnc the integral can be approximated by the famous simpson' rule ztnc / /dt nc nc tn the problem with this formula is that we do not know nc unc tnc and nc unc tnc as only un is available and only can then readily be computed to proceedthe idea is to use various approximations for nc and nc based on using well-known schemes for the ode in the intervals oetn tnc and oetn tnc let us split the integral into four termsztnc fonc fqnc fnnc / /dt tn where fonc fqnc and fnnc are approximations to nc and nc that can uti lize already computed quantities for fonc we can simply apply an approximation to unc based on forward euler step of size fonc un tnc ( this formula provides prediction of nc so we can for fqnc try backward euler method to approximate unc fqnc un fonc tnc ( with fqnc as an approximation to nc we can for the final term fnnc use midpoint method (or central differencealso called crank-nicolson methodto approximate unc fnnc un fonc tnc ( we have now used the forward and backward euler methods as well as the centered difference approximation in the context of simpson' rule the hope is that
3,886
the combination of these methods yields an overall time-stepping scheme from tn to tn that is much more accurate than the individual steps which have errors proportional to and this is indeed truethe numerical error goes in fact like ct for constant which means that the error approaches zero very quickly as we reduce the time step sizecompared to the forward euler method (error )the euler-cromer method (error tor the nd-order runge-kuttaor heun'smethod (error note that the th-order runge-kutta method is fully explicit so there is never any need to solve linear or nonlinear algebraic equationsregardless of what looks like howeverthe stability is conditional and depends on there is large family of implicit runge-kutta methods that are unconditionally stablebut require solution of algebraic equations involving at each time step the odespy package has support for lot of sophisticated explicit runge-kutta methodsbut not yet implicit runge-kutta methods more effectsdampingnonlinearityand external forces our model problem is the simplest possible mathematical model for oscillating systems neverthelessthis model makes strong demands to numerical methodsas we have seenand is very useful as benchmark for evaluating the performance of numerical methods real-life applications involve more physical effectswhich lead to differential equation with more terms and also more complicated terms typicallyone has damping force and spring force uboth these forces may depend nonlinearly on their argumentu or in additionenvironmental forces tmay act on the system for examplethe classical pendulum has nonlinear "springor restoring force usin /and air resistance on the pendulum leads to damping force ju ju examples on environmental forces include shaking of the ground ( due to an earthquakeas well as forces from waves and wind with three types of forces on the systemf and sthe sum of forces is written unote the minus sign in front of and swhich indicates that these functions are defined such that they represent forces acting against the motion for examplesprings attached to the wheels in car are combined with effective damperseach providing damping force bu that acts against the spring velocity the corresponding physical force is then bu which points downwards when the spring is being stretched (and points upwards)while acts upwards when the spring is being compressed (and points downwardsfigure shows an example of mass attached to potentially nonlinear spring and dashpotand subject to an environmental force tneverthelessour general model can equally well be pendulum as in fig with ud mg sin  (where cd : is the cross sectional area of the and up cd % bodyand is the density of airnewton' second law for the system can be written with the mass times acceleration on the left-hand side and the forces on the right-hand sidemu
3,887
solving ordinary differential equations fig general oscillating system fig pendulum with forces this equation ishowevermore commonly reordered to mu ud ( because the differential equation is of second orderdue to the term we need two initial conditionsu ( ud kuand td we recover the note that with the choices original ode with = how can we solve ( )as for the simple ode we start by rewriting the second-order ode as system of two first-order odes / the initial conditions become and ( (
3,888
any method for system of first-order odes can be used to solve for tand tthe euler-cromer scheme an attractive choice from an implementationalaccuracyand efficiency point of view is the euler-cromer scheme where we take forward difference in ( and backward difference in ( ) nc tn un / unc un nc ( ( we can easily solve for the new unknowns nc and unc tn un / unc un tv nc nc ( ( remark on the ordering of the odes the ordering of the odes in the ode system is important for the extended model ( )-( imagine that we write the equation for first and then the one for the euler-cromer method would then first use forward difference for unc and then backward difference for nc the latter would lead to nonlinear algebraic equation for nc nc nc tnc unc if vis nonlinear function of this would require numerical method for nonlinear algebraic equations to find nc while updating nc through forward difference gives an equation for nc that is linear and trivial to solve by hand the file osc_ec_general py has function eulercromer that implements this methoddef eulercromer(fsfmtu_ v_ dt)from numpy import zeroslinspace n_t int(round( /dt)print 'n_t:'n_t linspace( n_t*dtn_t+ zeros(n_t+ zeros(n_t+ initial condition [ u_ [ v_
3,889
solving ordinary differential equations step equations forward in time for in range(n_t) [ + [ndt*( / )*( ( [ ] ( [ ] ( [ ]) [ + [ndt* [ + return uvt the -th order runge-kutta method the rk method just evaluates the righthand side of the ode system /vm for known values of uvand tso the method is very simple to use regardless of how the functions uand vare chosen illustration of linear damping we consider an engineering system with linear springs ud kxand viscous damperwhere the damping force is proportional to bu for some constant this choice may model the vertical spring system in car (but engineers often like to illustrate such system by horizontal moving mass like the one depicted in fig we may choose simple values for the constants to illustrate basic effects of damping (and later excitationschoosing the oscillations to be the simple td cos function in the undamped casewe may set : the following function implements this casedef linear_damping() lambda vb* lambda uk* lambda u_ v_ *pi dt / uvt eulercromer( =fs=sf=fm=mt=tu_ =u_ v_ =v_ dt=dtplot_u(utthe plot_u function is collection of plot statements for plotting /or part of it figure shows the effect of the bu termwe have oscillations with (an approximateperiod as expectedbut the amplitude is efficiently damped remark about working with scaled problem instead of setting : and as fairly "unlikelyphysical valuesit would be better to scale the equation mu cbu cku this means
3,890
fig effect of linear damping that we introduce dimensionless independent and dependent variablestn tc un uc where tc and uc are characteristic sizes of time and displacementrespectivelysuch that tn and un have their typicalpsize around unity in the present problemwe can choose uc and tc = this gives the following scaled (or dimensionlessproblem for the dimensionless quantity tn/ un un cv un tn tn un vdp mk the striking fact is that there is only one physical parameter in this problemthe dimensionless number solving this problem corresponds to solving the original problem (with dimensionswith the parameters and howeversolving the dimensionless problem is more generalif we have solution tni /we can find the physical solution of range of problems since td un =mi as long as is fixedwe can find for any kand from the above formulain this waya time consuming simulation can be done only oncebut still provide many solutions this demonstrates the power of working with scaled or dimensionless problems
3,891
solving ordinary differential equations illustration of linear damping with sinusoidal excitation we now extend the previous example to also involve some external oscillating force on the systemf td sin wtdriving car on road with sinusoidal bumps might give such an external excitation on the spring system in the car ( is related to the velocity of the carwith : and from math import pisin lambda ta*sin( *twe get the graph in fig the striking difference from fig is that the oscillations start out as damped cos signal without much influence of the external forcebut then the free oscillations of the undamped system (cos tu die out and the external force : sin tinduces oscillations with shorter period = you are encouraged to play around with larger and switch from sine to cosine in and observe the effects if you look this up in physics bookyou can find exact analytical solutions to the differential equation problem in these cases particularly interesting case arises when the excitation force has the same frequency as the free oscillations of the undamped systemi td sin with the same amplitude : but smaller damping : the oscillations in fig becomes qualitatively very different as the amplitude grows significantly larger over some periods this phenomenon is called resonance and is exemplified in fig removing the damping results in an amplitude that grows linearly in time fig effect of linear damping in combination with sinusoidal external force
3,892
fig excitation force that causes resonance spring-mass system with sliding friction body with mass is attached to spring with stiffness while sliding on plane surface the body is also subject to friction force due to the contact between the body and the plane figure depicts the situation the friction force can be modeled by coulomb friction mgu mgu where is the friction coefficientand mg is the normal force on the surface where the body slides this formula can also be written as mg sign /profig sketch of one-dimensionaloscillating dynamic system subject to sliding friction and spring force
3,893
solving ordinary differential equations vided the signum function sign xis defined to be zero for (numpy sign has this propertyto check that the signs in the definition of are rightrecall that the actual physical force is and this is positive ( when it works against the body moving with velocity the nonlinear spring force is taken as ud tanh , /which is approximately ku for small ubut stabilizes at =for large , here is plot with and oe : : for three valuesif there is no external excitation force acting on the bodywe have the equation of motion mu mg sign tanh ,ud let us simulate situation where body of mass kg slides on surface with : while attached to spring with stiffness kg= the initial displacement of the body is cmand the parameter in uis set to / using the eulercromer function from the osc_ec_general codewe can write function sliding_friction for solving this problemdef sliding_friction()from numpy import tanhsign lambda vmu* * *sign(valpha lambda uk/alpha*tanh(alpha*uf lambda mu
3,894
fig effect of nonlinear (leftand linear (rightspring on sliding friction u_ v_ dt / uvt eulercromer( =fs=sf=fm=mt=tu_ =u_ v_ =v_ dt=dtplot_u(utrunning the sliding_friction function gives us the results in fig with ud tanh , (leftand the linearized version ud ku (righta finite difference methodundampedlinear case we shall now address numerical methods for the second-order ode without rewriting the ode as system of first-order odes the primary motivation for "yet another solution methodis that the discretization principles result in very good schemeand more importantlythe thinking around the discretization can be reused when solving partial differential equations the main idea of this numerical method is to approximate the second-order derivative by finite difference while there are several choices of difference approximations to first-order derivativesthere is one dominating formula for the second-order derivativeu tn unc un un ( the error in this approximation is proportional to letting the ode be valid at some arbitrary time point tn tn tn
3,895
solving ordinary differential equations we just insert the approximation ( to get unc un un un ( we now assume that un and un are already computed and that unc is the new unknown solving with respect to unc gives unc un un un ( major problem arises when we want to start the scheme we know that but applying ( for to compute leads to ( where we do not know the initial condition can help us to eliminate and this condition must anyway be incorporated in some way to this endwe discretize by centered differenceu it follows that and we can use this relation to eliminate in ( ) ( with and computed from ( )we can compute and so forth from ( exercise asks you to explore how the steps above are modified in case we have nonzero initial condition remark on simpler method for computing we could approximate the initial condition by forward differenceu leading to then we can use ( for the coming time steps howeverthis forward difference has an error proportional to twhile the centered difference we used has an error proportional to which is compatible with the accuracy (error goes like used in the discretization of the differential equation the method for the second-order ode described above goes under the name stormer' method or verlet integration it turns out that this method is mathematically equivalent with the euler-cromer scheme (!or more preciselythe general formula ( is equivalent with the euler-cromer formulabut the scheme for the
3,896
first time level ( implements the initial condition slightly more accurately than what is naturally done in the euler-cromer scheme the latter will do tv which differs from in ( by an amount because of the equivalence of ( with the euler-cromer schemethe numerical results will have the same nice properties such as constant amplitude there will be phase error as in the euler-cromer schemebut this error is effectively reduced by reducing tas already demonstrated the implementation of ( and ( is straightforward in function (file osc_ nd_order py)from numpy import zeroslinspace def osc_ nd_order(u_ omegadtt)""solve 'omega** * for in ( , ] ( )=u_ and '( )= by central finite difference method with time step dt ""dt float(dtnt int(round( /dt) zeros(nt+ linspace( nt*dtnt+ [ u_ [ [ *dt** *omega** * [ for in range( nt) [ + * [nu[ - dt** *omega** * [nreturn ut finite difference methodlinear damping key issue is how to generalize the scheme from sect to differential equation with more terms we start with the case of linear damping term bu possibly nonlinear spring force /and an excitation force /mu bu ud / ( we need to find the appropriate difference approximation to in the bu term good choice is the centered difference tn unc un sampling the equation at time point tn mu tn bu tn un tn /(
3,897
solving ordinary differential equations and inserting the finite difference approximations to and results in unc un un unc un cb un ( where is short notation for tn equation ( is linear in the unknown unc so we can easily solve for this quantity  unc mun un un / ( as in the case without dampingwe need to derive special formula for the initial condition implies also now that and with ( for we get ( / in the more general case with nonlinear damping term /mu ud /we get unc un un cf unc un un which is nonlinear algebraic equation for unc that must be solved by numerical methods much more convenient scheme arises from using backward difference for un un tn because the damping term will then be knowninvolving only un and un and we can easily solve for unc the downside of the backward difference compared to the centered difference ( is that it reduces the order of the accuracy in the overall scheme from to in factthe euler-cromer scheme evaluates nonlinear damping term as when computing nc and this is equivalent to using the backward difference above consequentlythe convenience of the euler-cromer scheme for nonlinear damping comes at cost of lowering the overall accuracy of the scheme from second to first order in using the same trick in the finite difference scheme for the second-order differential equationi using the backward difference in /makes this scheme equally convenient and accurate as the euler-cromer scheme in the general nonlinear case mu ud
3,898
exercises exercise geometric construction of the forward euler method section describes geometric interpretation of the forward euler method this exercise will demonstrate the geometric construction of the solution in detail consider the differential equation with we use time steps astart at and draw straight line with slope go one time step forward to and mark the solution point on the line bdraw straight line through the solution point tu with slope td go one time step forward to and mark the solution point on the line cdraw straight line through the solution point tu with slope td go one time step forward to and mark the solution point on the line dset up the forward euler scheme for the problem calculate and check that the numbers are the same as obtained in )-cfilenameforwardeuler_geometric_solution py exercise make test functions for the forward euler method the purpose of this exercise is to make file test_ode_fe py that makes use of the ode_fe function in the file ode_fe py and automatically verifies the implementation of ode_fe athe solution computed by hand in exercise can be used as reference solution make function test_ode_fe_ (that calls ode_fe to compute three time steps in the problem uu and compare the three values and with the values obtained in exercise bthe test in acan be made more general using the fact that if is linear in and does not depend on ti we have rufor some constant rthe forward euler method has closed form solution as outlined in sect un rt/ use this result to construct test function test_ode_fe_ (that runs number of steps in ode_fe and compares the computed solution with the listed formula for un filenametest_ode_fe py exercise implement and evaluate heun' method aa nd-order runge-kutta methodalso known has heun' methodis derived in sect make function ode_heun(fu_ dtt(as counterpart to ode_fe(fu_ dttin ode_fe pyfor solving scalar ode problem ut/ with this method using time step size bsolve the simple ode problem uu by the ode_heun and the ode_fe function make plot that compares heun' method and the forward euler method with the exact solution td for oe use time step :
3,899
solving ordinary differential equations cfor the case in )find through experimentation the largest value of where the exact solution and the numerical solution by heun' method cannot be distinguished visually it is of interest to see how far off the curve the forward euler method is when heun' method can be regarded as "exact(for visual purposesfilenameode_heun py exercise find an appropriate time steplogistic model compute the numerical solution of the logistic equation for set of repeatedly halved time stepstk tk plot the solutions corresponding to the last two time steps tk and tk in the same plot continue doing this until you cannot visually distinguish the two curves in the plot then one has found sufficiently small time step hint extend the logistic py file introduce loop over kwrite out tk and ask the user if the loop is to be continued filenamelogistic_dt py exercise find an appropriate time stepsir model repeat exercise for the sir model hint import the ode_fe function from the ode_system_fe module and make modified demo_sir function that has loop over repeatedly halved time steps plot si and versus time for the two last time step sizes in the same plot filenamesir_dt py exercise model an adaptive vaccination campaign in the sirv model with time-dependent vaccination from sect we want to test the effect of an adaptive vaccination campaign where vaccination is offered as long as half of the population is not vaccinated the campaign starts after days that isp if daysotherwise demonstrate the effect of this vaccination policychoose vand as in sect set : daysand simulate for days hint this discontinuous tfunction is easiest implemented as python function containing the indicated if test you may use the file sirv py as starting pointbut note that it implements time-dependent tvia an array filenamesirv_p_adapt py exercise make sirv model with time-limited effect of vaccination we consider the sirv model from sect but now the effect of vaccination is time-limited after characteristic period of timethe vaccination is no more effective and individuals are consequently moved from the to the category and can be infected again mathematicallythis can be modeled as an average leakage from the category to the category ( gain in the latter