id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
3,900 | write up the complete modelimplement itand rerun the case from sect with various choices of parameters to illustrate various effects filenamesirv _v py exercise refactor flat program consider the file osc_fe py implementing the forward euler method for the oscillating system model ( )-( the osc_fe py is what we often refer to as flat programmeaning that it is just one main program with no functions to easily reuse the numerical computations in other contextsplace the part that produces the numerical solution (allocation of arraysinitializing the arrays at time zeroand the time loopin function osc_fe(x_ omegadtt)which returns uvt place the particular computational example in osc_fe py in function demo(construct the file osc_fe_func py such that the osc_fe function can easily be reused in other programs in pythonthis means that osc_fe_func py is module that can be imported in other programs the requirement of module is that there should be no main programexcept in the test block you must therefore call demo from test block ( the block after if __name__ ='__main__'filenameosc_fe_func py exercise simulate oscillations by general ode solver solve the system ( )-( using the general solver ode_fe in the file ode_ system_fe py described in sect program the ode system and the call to the ode_fe function in separate file osc_ode_fe py equip this file with test function that reads file with correct values and compares these with those computed by the ode_fe function to find correct valuesmodify the program osc_fe py to dump the array to filerun osc_fe pyand let the test function read the reference results from that file filenameosc_ode_fe py exercise compute the energy in oscillations amake function osc_energy(uvomegafor returning the potential and kinetic energy of an oscillating system described by ( )-( the potential energy is taken as while the kinetic energy is (note that these expressions are not exactly the physical potential and kinetic energysince these would be mv and ku for model mx kx place the osc_energy in separate file osc_energy py such that the function can be called from other functions badd call to osc_energy in the programs osc_fe py and osc_ec py and plot the sum of the kinetic and potential energy how does the total energy develop for the forward euler and the euler-cromer schemesfilenamesosc_energy pyosc_fe_energy pyosc_ec_energy py |
3,901 | solving ordinary differential equations exercise use backward euler scheme for population growth we consider the ode problem td rn / at some timetn ntwe can approximate the derivative tn by backward differencesee fig tn tn tn tn which leads to rn called the backward euler scheme afind an expression for the in terms of and formulate an algorithm for computing bimplement the algorithm in ain function growth_be(n_ dttfor solving rn with time step (dtcimplement the forward euler scheme in function growth_fe(n_ dttas described in bdcompare visually the solution produced by the forward and backward euler schemes with the exact solution when and make two plotsone with : and one with : filenamegrowth_be py exercise use crank-nicolson scheme for population growth it is recommended to do exercise prior to the present one here we look at the same population growth model td rn / the time derivative tcan be approximated by various types of finite differences exercise considers backward difference (fig )while sect explained the forward difference (fig centered difference is more accurate than backward or forward difference tn tn nc tn td this type of differenceapplied at the point tnc tn tis illustrated geomet rically in fig ainsert the finite difference approximation in the ode rn and solve for the unknown nc assuming is already computed and hence known the resulting computational scheme is often referred to as crank-nicolson scheme bimplement the algorithm in ain function growth_cn(n_ dttfor solving rn with time step (dt |
3,902 | cmake plots for comparing the crank-nicolson scheme with the forward and backward euler schemes in the same test problem as in exercise filenamegrowth_cn py exercise understand finite differences via taylor series the taylor series around point can for function xbe written xd ac ax / ax ac dx dx ax / dx di ax / is dx for function of timeas addressed in our ode problemswe would use instead of instead of xand time point tn instead of au td tn tn tn / tn tn dt dt tn tn / dt di tn tn / is dt aa forward finite difference approximation to the derivative areads tn tn tn we can justify this formula mathematically through taylor series write up the taylor series for tn (around tn as given above)and then solve the expression with respect to tn identifyon the right-hand sidethe finite difference approximation and an infinite series this series is then the error in the finite difference approximation if is assumed small ( < ) will be much larger than which will be much larger than and so on the leading order term in the series for the errori the error with the least power of is good approximation of the error identify this term brepeat afor backward differenceu tn tn tn tt this timewrite up the taylor series for tn taround tn solve with respect to tn /and identify the leading order term in the error how is the error compared to the forward difference |
3,903 | solving ordinary differential equations ca centered difference approximation to the derivativeas explored in exercise can be written tn tn tn write up the taylor series for tn around tn and the taylor series for tn taround tn subtract the two seriessolve with respect to tn /identify the finite difference approximation and the error terms on the right-hand sideand write up the leading order error term how is this term compared to the ones for the forward and backward differencesdcan you use the leading order error terms in )-cto explain the visual observations in the numerical experiment in exercise efind the leading order error term in the following standard finite difference approximation to the second-order derivativeu tn tn tn tn tt hint express tn tvia taylor series and insert them in the difference formula filenametaylor_differences pdf exercise use backward euler scheme for oscillations consider ( )-( modeling an oscillating engineering system this ode system can be solved by the backward euler schemewhich is based on discretizing derivatives by collecting information backward in time more specificallyu tis approximated as tu tt general vector ode ut/where and are vectorscan use this approximation as followsun un un tn / which leads to an equation for the new value un un tf un tn un for general this is system of nonlinear algebraic equations howeverthe ode ( )-( is linearso backward euler scheme leads to system of two algebraic equations for two unknownsun tv un tu ( ( |
3,904 | asolve the system for un and bimplement the found formulas for un and in program for computing the entire numerical solution of ( )-( crun the program with corresponding to time steps per period of the oscillations (see sect for how to find such twhat do you observeincrease to time steps per period how much does this improve the solutionfilenameosc_be py remarks while the forward euler method applied to oscillation problems gives growing amplitudesthe backward euler method leads to significantly damped amplitudes exercise use heun' method for the sir model make program that computes the solution of the sir model from sect both by the forward euler method and by heun' method (or equivalentlythe nd-order runge-kutta methodfrom sect compare the two methods in the simulation case from sect make two comparison plotsone for large and one for small time step experiment to find what "largeand "smallshould bethe large one gives significant differenceswhile the small one lead to very similar curves filenamesir_heun py exercise use odespy to solve simple ode solve au bu by the odespy software let the problem parameters and be arguments to the right-hand side function that specifies the ode to be solved plot the solution for the case when =aand we use time intervals in oe filenameodespy_demo py exercise set up backward euler scheme for oscillations write the ode as system of two first-order odes and discretize these with backward differences as illustrated in fig the resulting method is referred to as backward euler scheme identify the matrix and right-hand side of the linear system that has to be solved at each time level implement the methodeither from scratch yourself or using odespy (the name is odespy backwardeulerdemonstrate that contrary to forward euler schemethe backward euler scheme leads to significant non-physical damping the figure below shows that even with time steps per periodthe results after few periods are useless |
3,905 | solving ordinary differential equations filenameosc_be py exercise set up forward euler scheme for nonlinear and damped oscillations derive forward euler method for the ode system ( )-( compare the method with the euler-cromer scheme for the sliding friction problem from sect does the forward euler scheme give growing amplitudes is the period of oscillation accurate what is the required time step size for the two methods to have visually coinciding curvesfilenameosc_fe_general py exercise discretize an initial condition assume that the initial condition on is nonzero in the finite difference method from sect derive the special formula for in this case filenameic_with_v_ pdf 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,906 | solving partial differential equations the subject of partial differential equations (pdesis enormous at the same timeit is very importantsince so many phenomena in nature and technology find their mathematical formulation through such equations knowing how to solve at least some pdes is therefore of great importance to engineers in an introductory book like thisnowhere near full justice to the subject can be made howeverwe still find it valuable to give the reader glimpse of the topic by presenting few basic and general methods that we will apply to very common type of pde we shall focus on one of the most widely encountered partial differential equationsthe diffusion equationwhich in one dimension looks like @ @ dv cg@ @ the multi-dimensional counterpart is often written as @ vr @ we shall restrict the attention here to the one-dimensional case the unknown in the diffusion equation is function xtof space and time the physical significance of depends on what type of process that is described by the diffusion equation for exampleu is the concentration of substance if the diffusion equation models transport of this substance by diffusion diffusion processes are of particular relevance at the microscopic level in biologye diffusive transport of certain ion types in cell caused by molecular collisions there is also diffusion of atoms in solidfor instanceand diffusion of ink in glass of water one very popular application of the diffusion equation is for heat transport in solid bodies then is the temperatureand the equation predicts how the temperature evolves in space and time within the solid body for such applicationsthe equation is known as the heat equation we remark that the temperature in fluid is influenced not only by diffusionbut also by the flow of the liquid if presentthe latter effect requires an extra term in the equation (known as an advection or convection termthe term is known as the source term and represents generationor lossof heat (by some mechanismwithin the body for diffusive transportg models injection or extraction of the substance (cthe author( lingeh langtangenprogramming for computations pythontexts in computational science and engineering doi -- |
3,907 | solving partial differential equations we should also mention that the diffusion equation may appear after simplifying more complicated partial differential equations for exampleflow of viscous fluid between two flat and parallel plates is described by one-dimensional diffusion equationwhere then is the fluid velocity partial differential equation is solved in some domain in space and for time interval oe the solution of the equation is not unique unless we also prescribe initial and boundary conditions the type and number of such conditions depend on the type of equation for the diffusion equationwe need one initial conditionu /stating what is when the process starts in additionthe diffusion equation needs one boundary condition at each point of the boundary @of this condition can either be that is known or that we know the normal derivativeru @ =@ ( denotes an outward unit normal to @"let us look at specific application and how the diffusion equation with initial and boundary conditions then appears we consider the evolution of temperature in one-dimensional mediummore precisely long rodwhere the surface of the rod is covered by an insulating material the heat can then not escape from the surfacewhich means that the temperature distribution will only depend on coordinate along the rodxand time at one end of the rodx lwe also assume that the surface is insulatedbut at the other endx we assume that we have some device for controlling the temperature of the medium herea function ttells what the temperature is in time we therefore have boundary condition td tat the other insulated endx lheat cannot escapewhich is expressed by the boundary condition @ lt/=@ the surface along the rod is also insulated and hence subject to the same boundary condition (here generalized to @ =@ at the curved surfacehoweversince we have reduced the problem to one dimensionwe do not need this physical boundary condition in our mathematical model in one dimensionwe can set oe lto summarizethe partial differential equation with initial and boundary conditions reads @ xt@ xtc xt/dv @ @ td / ltd @ / ; ( ( ( oe ( mathematicallywe assume that at the initial condition ( holds and that the partial differential equation ( comes into play for similarlyat the end pointsthe boundary conditions ( and ( govern and the equation therefore is valid for lboundary and initial conditions are neededthe initial and boundary conditions are extremely important without themthe solution is not uniqueand no numerical method will work unfortunatelymany physical applications have one or more initial or boundary conditions as unknowns such situations can be dealt with if we have measurements of ubut the mathematical framework is much more complicated |
3,908 | what about the source term in our example with temperature distribution in rodg xtmodels heat generation inside the rod one could think of chemical reactions at microscopic level in some materials as reason to include howeverin most applications with temperature evolutiong is zero and heat generation usually takes place at the boundary (as in our example with td /before continuingwe may consider an example of how the temperature distribution evolves in the rod at time we assume that the temperature is then we suddenly apply device at that keeps the temperature at at this end what happens inside the rodintuitivelyyou think that the heat generation at the end will warm up the material in the vicinity of and as time goes bymore and more of the rod will be heatedbefore the entire rod has temperature of (recall that no heat escapes from the surface of the rodmathematically(with the temperature in kelvinthis example has xd kexcept at the end pointi ks td kand the figure below shows snapshots from four different times in the evolution of the temperature finite difference methods we shall now construct numerical method for the diffusion equation we know how to solve ordinary differential equationsso in way we are able to deal with the time derivative very often in mathematicsa new problem can be solved by reducing it to series of problems we know how to solve in the present caseit means that we must do something with the spatial derivative @ =@ in order |
3,909 | solving partial differential equations to reduce the partial differential equation to ordinary differential equations one important technique for achieving thisis based on finite difference discretization of spatial derivatives reduction of pde to system of odes introduce spatial mesh in with mesh points xn the space between two mesh points xi and xi the interval oexi xi is call cell we shall herefor simplicityassume that each cell has the same length xi xi the partial differential equation is valid at all spatial points "but we may relax this condition and demand that it is fulfilled at the internal mesh points onlyx xn @ xi @ xi tc xi /dv @ @ ( nowat any point xi we can approximate the second-order derivative by finite difference@ xi tu xi xi tc xi ( @ it is common to introduce short notation ui tfor xi / approximated at some mesh point xi in space with this new notation we canafter inserting ( in ( )write an approximation to the partial differential equation at mesh point xi tas dui tui ui tc ui tc gi /dv dt ( note that we have adopted the notation gi tfor xi ttoo what is ( )this is nothing but system of ordinary differential equations in unknowns /un /in other wordswith aid of the finite difference approximation ( )we have reduced the single partial differential equation to system of odeswhich we know how to solve in the literaturethis strategy is called the method of lines we need to look into the initial and boundary conditions as well the initial condition xtranslates to an initial condition for every unknown function ui /ui xi / at the boundary we need an ode in our ode systemwhich must come from the boundary condition at this point the boundary condition reads td twe can derive an ode from this equation by differentiating both sidesu td tthe ode system above cannot be used for since that equation involves some quantity outside the domain insteadwe use the equation td tderived from the boundary condition for this particular equation we also need to make sure the initial condition is (otherwise nothing will happenwe get forever |
3,910 | we remark that separate ode for the (knownboundary condition tis not strictly needed we can just work with the ode system for un and in the ode for replace tby thoweverthese authors prefer to have an ode for every point value ui which requires formulating the known boundary at as an ode the reason for including the boundary values in the ode system is that the solution of the system is then the complete solution at all mesh pointswhich is convenientsince special treatment of the boundary values is then avoided the condition @ =@ at is bit more complicatedbut we can approximate the spatial derivative by centered finite differencev @ vv un un @ dn this approximation involves fictitious point xn outside the domain common trick is to use ( for and eliminate un by use of the discrete boundary condition (un un )dun un un tc gn tdv dt ( that iswe have special version of ( at the boundary what about simpler finite differences at the boundarysome reader may think that smarter trick is to approximate the boundary condition @ =@ at by one-sided differencev @ vv un un @ vi dn this gives simple equation un un for the boundary valueand corresponding ode howeverthis approximation has an error of order xwhile the centered approximation we used above has an error of order the finite difference approximation we used for the second-order derivative in the diffusion equation also has an error of order thusif we use the simpler one-sided difference aboveit turns out that we reduce the overall accuracy of the method we are now in position to summarize how we can approximate the partial differential equation problem ( )-( by system of ordinary differential equationsdu /dt dui ui ui tc ui / gi / dt dun un un / gn td dt ( ( ( |
3,911 | solving partial differential equations the initial conditions are /ui xi / ( ( we can apply any method for systems of odes to solve ( )-( construction of test problem with known discrete solution at this pointit is tempting to implement real physical case and run it howeverpartial differential equations constitute non-trivial topic where mathematical and programming mistakes come easy better start is therefore to address carefully designed test example where we can check that the method works the most attractive examples for testing implementations are those without approximation errorsbecause we know exactly what numbers the program should produce it turns out that solutions xtthat are linear in time and in space can be exactly reproduced by most numerical methods for partial differential equations candidate solution might be xtd linserting this in the governing equation gives ld xtg xtd lwhat about the boundary conditionswe realize that @ =@ for lwhich breaks the assumption of @ =@ at in the formulation of the numerical method above moreoveru td /so we must set td tc and td finallythe initial condition dictates xd xl/but recall that we must have /and ui xi / it is important that starts out at the right value dictated by tin case is not equal this value first we need to generalize our method to handle @ =@ $ at we then have un un td un un xwhich inserted in ( gives dun un tc un tc gn tdv dt ( implementationforward euler method in particularwe may use the forward euler method as implemented in the general function ode_fe in the module ode_system_fe from sect the ode_fe function needs specification of the right-hand side of the ode system |
3,912 | this is matter of translating ( )( )and ( to python code (in file test_diffusion_pde_exact_linear py)def rhs(ut) len( rhs zeros( + rhs[ dsdt(tfor in range( )rhs[ (beta/dx** )*( [ + * [iu[ - ] ( [ ]trhs[ (beta/dx** )*( * [ - *dx*dudx( * [ ] ( [ ]treturn rhs def u_exact(xt)return ( * )*( ldef dudx( )return ( * def ( )return u_exact( tdef dsdt( )return *(-ldef (xt)return *( -lnote that dudx(tis the function representing the parameter in ( also note that the rhs function relies on access to global variables betadxland xand global functions dsdtgand dudx we expect the solution to be correct regardless of and tso we can choose small and : test function with goes like def test_diffusion_exact_linear()global betadxlx needed in rhs beta linspace( ln+ dx [ [ zeros( + u_ zeros( + u_ [ ( u_ [ :u_exact( [ :] dt print dt ut ode_fe(rhsu_ dtt= |
3,913 | solving partial differential equations tol - for in range( shape[ ])diff abs(u_exact(xt[ ] [ ,:]max(assert diff tol'diff= gdiff print 'diff=% at =% (difft[ ]with we reproduce the linear solution exactly this brings confidence to the implementationwhich is just what we need for attacking real physical problem next problems with reusing the rhs function the rhs function must take and as argumentsbecause that is required by the ode_fe function what about the variables betadxlxdsdtgand dudx that the rhs function needsthese are global in the solution we have presented so far unfortunatelythis has an undesired side effectwe cannot import the rhs function in new filedefine dudx and dsdt in this new file and get the imported rhs to use these functions the imported rhs will use the global variablesincluding functionsin its own module how can we find solutions to this problemtechnicallywe must pack the extra data betadxlxdsdtgand dudx with the rhs functionwhich requires more advanced programming considered beyond the scope of this text class is the simplest construction for packing function together with datasee the beginning of in [ for detailed example on how classes can be used in such context another solution in pythonand especially in computer languages supporting functional programmingis so called closures they are also covered in in the mentioned reference and behave in magic way the third solution is to allow an arbitrary set of arguments for rhs in list to be transferred to ode_fe and then back to rhs appendix in [ explains the technical details applicationheat conduction in rod let us return to the case with heat conduction in rod ( )-( assume that the rod is cm long and made of aluminum alloy the parameter equals % /where is the heat conduction coefficientis the densityand is the heat capacity we can find proper values for these physical quantities in the case of this aluminum alloy : kg/ mk kkg results in %cd : = preliminary simulations show that we are close to constant steady state temperature after hi the rhs function from the previous section can be reusedonly the functions sdsdtgand dudx must be changed (see file rod_fe py)def dudx( )return def ( )return |
3,914 | def dsdt( )return def (xt)return parameters can be set as beta - linspace( ln+ dx [ [ zeros( + u_ zeros( + u_ [ ( u_ [ : let us use : we can now call ode_fe and then make an animation on the screen to see how xtdevelops in timet time clock(from ode_system_fe import ode_fe ut ode_fe(rhsu_ dtt= * * time clock(print 'cpu time fs( make movie import os os system('rm tmp_png'import matplotlib pyplot as plt plt ion( [ ,:lines plt plot(xyplt axis([ [ ] [- ] ( )+ ]plt xlabel(' 'plt ylabel(' ( , )'counter plot each of the first framesthen increase speed by change_speed for in range( shape[ ])print [iplot true if <change_speed else = lines[ set_ydata( [ ,:]if change_speedplt legend([' = xt[ ]]elseplt legend([' = ft[ ]]plt draw(if plotplt savefig('tmp_% pngcountercounter + #time sleep( |
3,915 | solving partial differential equations the plotting statements update the xtcurve on the screen in additionwe save fraction of the plots to files tmp_ pngtmp_ pngtmp_ pngand so on these plots can be combined to ordinary video files common tool is ffmpeg or its sister avconv these programs take the same type of command-line options to make flash video movie flvrun terminal terminalffmpeg - tmp_% png - -vcodec flv movie flv the - option specifies the naming of the plot files in printf syntaxand - specifies the number of frames per second in the movie on macrun ffmpeg instead of avconv with the same options other video formatssuch as mp webmand ogg can also be producedterminal terminalffmpeg - tmp_% png - -vcodec libx movie mp terminalffmpeg - tmp_% png - -vcodec libvpx movie webm terminalffmpeg - tmp_% png - -vcodec libtheora movie ogg the results of simulation start out as in figs and we see that the solution definitely looks wrong the temperature is expected to be smoothnot having such saw-tooth shape alsoafter some time (fig )the temperature starts to increase much more than expected we say that this solution is unstablemeaning that it does not display the same characteristics as the truephysical solution even though we tested the code carefully in the previous sectionit does not seem to work for physical applicationhow can that bethe problem is that is too largemaking the solution unstable it turns out that the forward euler time integration method puts restriction on the size of for the heat equation and the way we have discretized itthis restriction can be shown to be [ ( this is called stability criterion with the chosen parameters( tells us that the upper limit is : which is smaller than our choice above rerunning the case with equal to /indeed shows smooth evolution of xtfind the program rod_fe py and run it to see an animation of the xtfunction on the screen scaling and dimensionless quantities our setting of parameters required finding three physical properties of certain material the time interval for simulation and the time step depend crucially on the values for and lwhich can vary significantly from case to case oftenwe are more interested in how the shape of xtdevelopsthan in the actual uxand values for specific material we can then simplify the setting of physical parameters by scaling the problem |
3,916 | fig unstable simulation of the temperature in rod fig unstable simulation of the temperature in rod |
3,917 | solving partial differential equations scaling means that we introduce dimensionless independent and dependent variableshere denoted by barun uu uc xn xc tn tc where uc is characteristic size of the temperatureu is some reference temperaturewhile xc and tc are characteristic time and space scales hereit is natural to choose as the initial conditionand set uc to the stationary (endtemperature then un oe starting at and ending at as the length is xc while choosing tc is more challengingbut one can argue for tc = the resulting equation for un reads @un @ un @tn @xn xn note that in this equationthere are no physical parametersin other wordswe have found model that is independent of the length of the rod and the material it is made of (!we can easily solve this equation with our program by setting xd and td it turns out that the total simulation time (to "infinity"can be taken as when we have the solution xn tn/the solution with dimension kelvinreflecting the true temperature in our mediumis given by tv= xtd uc / =lthrough this formula we can quickly generate the solutions for rod made of aluminumwoodor rubber it is just matter of plugging in the right value figure shows four snapshots of the scaled (dimensionlesssolution nxn tnthe power of scaling is to reduce the number of physical parameters in problemand in the present casewe found one single problem that is independent of the material (vand the geometry (lvectorization occasionally in this bookwe show how to speed up code by replacing loops over arrays by vectorized expressions the present problem involves loop for computing the right-hand sidefor in range( )rhs[ (beta/dx** )*( [ + * [iu[ - ] ( [ ]tthis loop can be replaced by vectorized expression with the following reasoning we want to set all the inner points at oncerhs[ : - (this goes from index up tobut not includingnas the loop index runs from to - the [ + term will cover all the inner values displaced one index to the right (compared to : - ) [ :nsimilarlyu[ - corresponds to all inner values displaced one index to the leftu[ : - finallyu[ihas the same indices as rhsu[ : - the vectorized loop can therefore be written in terms of slices |
3,918 | fig snapshots of the dimensionless solution of scaled problem rhs[ : - (beta/dx** )*( [ : + * [ :nu[ : - ] ( [ : ]tthis rewrite speeds up the code by about factor of complete code is found in the file rod_fe_vec py using odespy to solve the system of odes let us now show how to apply general ode package like odespy (see sect to solve our diffusion problem as long as we have defined right-hand side function rhs this is very straightforwardimport odespy solver odespy rkfehlberg(rhssolver set_initial_condition(u_ n_t int(round( /float(dt))time_points linspace( tn_t+ ut solver solve(time_points |
3,919 | solving partial differential equations fig time steps used by the runge-kutta-fehlberg methoderror tolerance (leftand (rightcheck how many time steps are required by adaptive vs fixed-step methods if hasattr(solver't_all')print 'time steps:'len(solver t_allelseprint 'time steps:'len(tthe very nice thing is that we can now easily experiment with many different integration methods trying out some simple ones firstlike rk and rk quickly reveals that the time step limitation of the forward euler scheme also applies to these more sophisticated runge-kutta methodsbut their accuracy is better howeverthe odespy package offers also adaptive methods we can then specify much larger time step in time_pointsand the solver will figure out the appropriate step above we indicated how to use the adaptive runge-kutta-fehlberg - solver while the corresponding to the forward euler method requires over steps for simulationwe started the rkfehlberg method with times this time step and in the end it required just slightly more than stepsusing the default tolerance parameters lowering the tolerance did not save any significant amount of computational work figure shows comparison of the length of all the time steps for two values of the tolerance we see that the influence of the tolerance is minor in this computational exampleso it seems that the blow-up due to instability is what governs the time step size the nice feature of this adaptive method is that we can just specify when we want the solution to be computedand the method figures out on its own what time step that has to be used because of stability restrictions we have seen how easy it is to apply sophisticated methods for odes to this pde example we shall take the use of odespy one step further in the next section implicit methods major problem with the stability criterion ( is that the time step becomes very small if is small for examplehalving requires four times as many time steps and eight times the work nowwith which is reasonable resolution for the test problem abovethe computations are very fast what takes |
3,920 | timeis the visualization on the screenbut for that purpose one can visualize only subset of the time steps howeverthere are occasions when you need to take larger time steps with the diffusion equationespecially if interest is in the longterm behavior as you must then turn to implicit methods for odes these methods require the solutions of linear systemsif the underlying pde is linearand systems of nonlinear algebraic equations if the underlying pde is non-linear the simplest implicit method is the backward euler schemewhich puts no restrictions on for stabilitybut obviouslya large leads to inaccurate results the backward euler scheme for scalar ode utreads unc un unc tnc this equation is to be solved for unc if is linear in uit is linear equationbut if is nonlinear in uone needs approximate methods for nonlinear equations (chap in our casewe have system of linear odes ( )-( the backward euler scheme applied to each equation leads to un unc tnc / uni unc unc unc unc gi tnc / unc unn nc unc gi tnc ( ( ( which this is system of linear equations in the unknowns unc is easy to realize by writing out the equations for the case collecting all the unknown terms on the left-hand side and all the known terms on the right-hand sideunc un tnc / unc unc unc tnc / nc unc unc tnc unc ( ( ( system of linear equations like thisis usually written on matrix form au bnc where is coefficient matrixu unc nn is the vector of unknownsand is vector of known values the coefficient matrix for the case ( )-( becomes |
3,921 | solving partial differential equations in the general case ( )-( )the coefficient matrix is an matrix with zero entriesexcept for ; ai; ai; ai; an; an; ( ( ( ( ( ( if we want to apply general methods for systems of odes on the form ut/we can assume linear utd ku the coefficient matrix is found from the right-hand side of ( )-( to be ; ki; ki; kn; kn; ki; ( ( ( ( ( ( we see that to implement the backward euler schemewe can either fill matrix and call linear solveror we can apply odespy we follow the latter strategy implicit methods in odespy need the matrix abovegiven as an argument jac (jacobian of in the call to odespy backwardeuler here is the python code for the right-hand side of the ode system (rhsand the matrix (kas well as statements for initializing and running the odespy solver backwardeuler (in the file rod_be py)def rhs(ut) len( rhs zeros( + rhs[ dsdt(tfor in range( )rhs[ (beta/dx** )*( [ + * [iu[ - ] ( [ ]trhs[ (beta/dx** )*( * [ - *dx*dudx( * [ ] ( [ ]treturn rhs |
3,922 | def (ut) len( zeros(( + , + ) [ , for in range( ) [ , - beta/dx** [ , - *beta/dx** [ , + beta/dx** [ , - (beta/dx** )* [ , (beta/dx** )*(- return import odespy solver odespy backwardeuler(rhsf_is_linear=truejac=ksolver odespy thetarule(rhsf_is_linear=truejac=ktheta= solver set_initial_condition(u_ * * n_t int(round( /float(dt))time_points linspace( tn_t+ ut solver solve(time_pointsthe file rod_be py has all the details and shows movie of the solution we can run it with any we wantits size just impacts the accuracy of the first steps odespy solvers apply dense matriceslooking at the entries of the matrixwe realize that there are at maximum three entries different from zero in each row thereforemost of the entries are zeroes the odespy solvers expect dense square matrices as inputhere with elements when solving the linear systemsa lot of storage and work are spent on the zero entries in the matrix it would be much more efficient to store the matrix as tridiagonal matrix and apply specialized gaussian elimination solver for tridiagonal systems actuallythis reduces the work from the order to the order in one-dimensional diffusion problemsthe savings of using tridiagonal matrix are modest in practicesince the matrices are very small anyway in twoand three-dimensional pde problemshoweverone cannot afford dense square matrices ratherone must resort to more efficient storage formats and algorithms tailored to such formatsbut this is beyond the scope of the present text exercises exercise simulate diffusion equation by hand consider the problem given by ( )( and ( set and compute and by hand for use these values to construct test function for checking that the implementation is correct copy useful functions from test_diffusion_pde_exact_linear py and make new test function test_diffusion_hand_calculation filenametest_rod_hand_calculations py |
3,923 | solving partial differential equations exercise compute temperature variations in the ground the surface temperature at the ground shows daily and seasonal oscillations when the temperature rises at the surfaceheat is propagated into the groundand the coefficient in the diffusion equation determines how fast this propagation is it takes some time before the temperature rises down in the ground at the surfacethe temperature has then fallen we are interested in how the temperature varies down in the ground because of temperature oscillations on the surface assuming homogeneous horizontal properties of the groundat least locallyand no variations of the temperature at the surface at fixed point of timewe can neglect the horizontal variations of the temperature then one-dimensional diffusion equation governs the heat propagation along vertical axis called the surface corresponds to and the axis point downwards into the ground there is no source term in the equation (actuallyif rocks in the ground are radioactivethey emit heat and that can be modeled by source termbut this effect is neglected hereat some depth we assume that the heat changes in vanishso @ =@ is an appropriate boundary condition at we assume simple sinusoidal temperature variation at the surface td ta sin where is the periodtaken here as hours ( sthe coefficient may be set to = time is then measured in seconds set appropriate values for and ta ashow that the present problem has an analytical solution of the form xtd be rx sin ! rx/for appropriate values of abrand bsolve this heat propagation problem numerically for some days and animate the temperature you may use the forward euler method in time plot both the numerical and analytical solution as initial condition for the numerical solutionuse the exact solution during program developmentand when the curves coincide in the animation for all timesyour implementation worksand you can then switch to constant initial conditionu for this latter initial conditionhow many periods of oscillations are necessary before there is good (visualmatch between the numerical and exact solution (despite differences at )filenameground_temp py exercise compare implicit methods an equally stablebut more accurate method than the backward euler schemeis the so-called -step backward schemewhich for an ode utcan be expressed by unc un un unc tnc |
3,924 | the odespy package offers this method as odespy backward step the purpose of this exercise is to compare three methods and animate the three solutions the backward euler method with : the backward -step method with : the backward -step method with : choose the model problem from sect filenamerod_be_vs_b step py exercise explore adaptive and implicit methods we consider the same problem as in exercise now we want to explore the use of adaptive and implicit methods from odespy to see if they are more efficient than the forward euler method assume that you want the accuracy provided by the forward euler method with its maximum value since there exists an analytical solutionyou can compute an error measure that summarizes the error in space and time over the whole simulations xx uin uni / xt hereuin is the exact solution use the odespy package to run the following implicit and adaptive solvers backwardeuler backward step rkfehlberg experiment to see if you can use larger time steps than what is required by the forward euler method and get solutions with the same order of accuracy hint to avoid oscillations in the solutions when using the rkfehlberg methodthe rtol and atol parameters to rkffehlberg must be set no larger than and respectively you can print out solver_rkf t_all to see all the time steps used by the rkfehlberg solver (if solver is the rkfehlberg objectyou can then compare the number of time steps with what is required by the other methods filenameground_temp_adaptive py exercise investigate the rule athe crank-nicolson method for odes is very popular when combined with diffusion equations for linear ode au it reads unc un aun aunc apply the crank-nicolson method in time to the ode system for onedimensional diffusion equation identify the linear system to be solved |
3,925 | solving partial differential equations bthe backward eulerforward eulerand crank-nicolson methods can be given unified implementation for linear ode au this formulation is known as the ruleunc un /aun aunc for we recover the forward euler methodd gives the backward euler schemeand = corresponds to the crank-nicolson method the approximation error in the rule is proportional to texcept for = where it is proportional to for = the method is stable for all apply the rule to the ode system for one-dimensional diffusion equation identify the linear system to be solved cimplement the rule with aid of the odespy package the relevant object name is thetarulesolver odespy thetarule(rhsf_is_linear=truejac=ktheta= dconsider the physical application from sect run this case with the rule and = for the following values of report what you see filenamerod_thetarule py remarks despite the fact that the crank-nicolson methodor the rule with = is theoretically more accurate than the backward euler and forward euler schemesit may exhibit non-physical oscillations as in the present example if the solution is very steep the oscillations are damped in timeand decreases with decreasing to avoid oscillations one must have at maximum twice the stability limit of the forward euler method this is one reason why the backward euler method (or -step backward schemesee exercise are popular for diffusion equations with abrupt initial conditions exercise compute the diffusion of gaussian peak solve the following diffusion problem@ @ @ @ exp td @ td @ / ( oe ( ( ( the initial condition is the famous and widely used gaussian function with standard deviation (or "width"which is here taken to be smalld : such that the initial condition is peak this peak will then diffuse and become lower and wider compute xtuntil becomes approximately constant over the domain filenamegaussian_diffusion py |
3,926 | remarks running the simulation with : results in constant solution as while one might expect from "physics of diffusionthat the solution should approach zero the reason is that we apply neumann conditions as boundary conditions one can then easily show that the area under the curve remains constant integrating the pde gives @ dx @ @ dx @ using the gauss divergence theorem on the integral on the right-hand and moving the time-derivative outside the integral on the left-hand side results in @ xt/dx @du @ (recall that @ =@ at the end points the result means that udx remains constant during the simulation giving the pde an interpretation in terms of heat conduction can easily explain the resultwith neumann conditions no heat can escape from the domain so the initial heat will just be evenly distributedbut not leak outso the temperature cannot go to zero (or the scaled and translated temperature uto be precisethe area under the initial condition is so with sufficiently fine meshu regardless of exercise vectorize function for computing the area of polygon vectorize the implementation of the function for computing the area of polygon in exercise make test function that compares the scalar implementation in exercise and the new vectorized implementation for the test cases used in exercise pn hint notice that the formula xn yn xi yi is the dot product of two vectorsx[:- and [ :]which can be computed as numpy dot( [:- ] [ :])or more explicitly as numpy sum( [:- ]* [ :]filenamepolyarea_vec py exercise explore symmetry one can observe (and also mathematically provethat the solution xtof the problem in exercise is symmetric around xtd xtin such casewe can split the domain in two and compute in only one halfoe or oe at the symmetry line we have the symmetry boundary condition @ =@ reformulate the problem in exercise such that we compute only for oe display the solution and observe that it equals the right part of the solution in exercise filenamesymmetric_gaussian_diffusion py |
3,927 | solving partial differential equations remarks in and problemswhere the cpu time to compute solution of pde can be hours and daysit is very important to utilize symmetry as we do above to reduce the size of the problem also note the remarks in exercise about the constant area under the xtcurveherethe area is and : as : (if the mesh is sufficiently fine one will get convergence to smaller values for small if the mesh is not fine enough to properly resolve thin-shaped initial conditionexercise compute solutions as many diffusion problems reach stationary time-independent solution as the model problem from sect is one example where xtd td const for when does not depend on timethe diffusion equation reduces to vu xd /in one dimensionand vr /in and this is the famous poisson equationor if it is known as the laplace equation in this limit there is no need for an initial conditionbut the boundary conditions are the same as for the diffusion equation we now consider one-dimensional problem xd / cu ld ( which is known as two-point boundary value problem this is nothing but the stationary limit of the diffusion problem in sect how can we solve such stationary problem ( )the simplest strategywhen we already have solver for the corresponding time-dependent problemis to use that solver and simulate until which in practice means that xtno longer changes in time (within some tolerancea nice feature of implicit methods like the backward euler scheme is that one can take one very long time step to "infinityand produce the solution of ( alet ( be valid at mesh points xi in spacediscretize by finite differenceand set up system of equations for the point values ui , where ui is the approximation at mesh point xi bshow that if in ( ( )it leads to the same equations as in acdemonstrateby running programthat you can take one large time step with the backward euler scheme and compute the solution of ( the solution is very boring since it is constantu xd filenamerod_stationary py remarks if the interest is in the stationary limit of diffusion equationone can either solve the associated laplace or poisson equation directlyor use backward euler scheme for the time-dependent diffusion equation with very long time step using forward euler scheme with small time steps is typically inappropriate in |
3,928 | such situations because the solution changes more and more slowlybut the time step must still be kept smalland it takes "foreverto approach the stationary state this is yet another example why one needs implicit methods like the backward euler scheme exercise solve two-point boundary value problem solve the following two-point boundary-value problem xd / hint do exercise modify the boundary condition in the code so it incorporates known value for filename ptbvp py 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,929 | solving nonlinear algebraic equations as reader of this book you are probably well into mathematics and often "accusedof being particularly good at "solving equations( typical comment at family dinners!howeveris it really true that youwith pen and papercan solve many types of equationsrestricting our attention to algebraic equations in one unknown xyou can certainly do linear equationsax and quadratic onesax bx you may also know that there are formulas for the roots of cubic and quartic equations too maybe you can do the special trigonometric equation sin cos as wellbut there it (probablystops equations that are not reducible to one of the mentioned cannot be solved by general analytical techniqueswhich means that most algebraic equations arising in applications cannot be treated with pen and paperif we exchange the traditional idea of finding exact solutions to equations with the idea of rather finding approximate solutionsa whole new world of possibilities opens up with such an approachwe can in principle solve any algebraic equation let us start by introducing common generic form for any algebraic equationf xd heref xis some prescribed formula involving for examplethe equation sin cos (cthe author( lingeh langtangenprogramming for computations pythontexts in computational science and engineering doi -- |
3,930 | solving nonlinear algebraic equations has xd sin cos just move all terms to the left-hand side and then the formula to the left of the equality sign is xsowhen do we really need to solve algebraic equations beyond the simplest types we can treat with pen and paperthere are two major application areas one is when using implicit numerical methods for ordinary differential equations these give rise to one or system of algebraic equations the other major application type is optimizationi finding the maxima or minima of function these maxima and minima are normally found by solving the algebraic equation xd if xis the function to be optimized differential equations are very much used throughout science and engineeringand actually most engineering problems are optimization problems in the endbecause one wants design that maximizes performance and minimizes cost we first consider one algebraic equation in one variablewith our usual emphasis on how to program the algorithms systems of nonlinear algebraic equations with many variables arise from implicit methods for ordinary and partial differential equations as well as in multivariate optimization our attention will be restricted to newton' method for such systems of nonlinear algebraic equations terminology when solving algebraic equations xd we often say that the solution is root of the equation the solution process itself is thus often called root finding brute force methods the representation of mathematical function xon computer takes two forms one is python function returning the function value given the argumentwhile the other is collection of points xf /along the function curve the latter is the representation we use for plottingtogether with an assumption of linear variation between the points this representation is also very suited for equation solving and optimizationwe simply go through all points and see if the function crosses the axisor for optimizationtest for local maximum or minimum point because there is lot of work to examine huge number of pointsand also because the idea is extremely simplesuch approaches are often referred to as brute force methods howeverwe are not embarrassed of explaining the methods in detail and implementing them |
3,931 | brute force methods brute force root finding assume that we have set of points along the curve of function /we want to solve xd find the points where crosses the axis brute force algorithm is to run through all points on the curve and check if one point is below the axis and if the next point is above the axisor the other way around if this is found to be the casewe know that must be zero in between these two points numerical algorithm more preciselywe have set of points xi yi /yi xi / nwhere (or the other way arounda compact expression for this check is to perform the test yi yi if sothe root of xd is in oexi xi assuming linear variation of between xi and xi we have the approximation xyi yi xi xi xi xi xi yi xi xi xi xi whichwhen set equal to zerogives the root xi xi xi yi yi yi implementation given some python implementation (xof our mathematical functiona straightforward implementation of the above numerical algorithm looks like |
3,932 | solving nonlinear algebraic equations linspace( (xroot none initialization for in range(len( )- )if [ ]* [ + root [ ( [ + [ ])/( [ + [ ])* [ibreak jump out of loop if root is noneprint 'could not find any root in [% % ]( [ ] [- ]elseprint 'find (the firstroot as =%groot (see the file brute_force_root_finder_flat py note the nice use of setting root to nonewe can simply test if root is none to see if we found root and overwrote the none valueor if we did not find any root among the tested points running this program with some functionsay xd cos (which has solution at )gives the root which has an error of : increasing the number of points with factor of ten gives root with an error of : after such quick "flatimplementation of an algorithmwe should always try to offer the algorithm as python functionapplicable to as wide problem domain as possible the function should take and an associated interval oeabas inputas well as number of points ( )and return list of all the roots in oeabhere is our candidate for good implementation of the brute force rooting finding algorithmdef brute_force_root_finder(fabn)from numpy import linspace linspace(abny (xroots [for in range( - )if [ ]* [ + root [ ( [ + [ ])/( [ + [ ])* [iroots append(rootreturn roots (see the file brute_force_root_finder_function py this time we use another elegant technique to indicate if roots were found or notroots is an empty list if the root finding was unsuccessfulotherwise it contains all the roots application of the function to the previous example can be coded as def demo()from numpy import expcos roots brute_force_root_finderlambda xexp(- ** )*cos( * ) if rootsprint roots elseprint 'could not find any roots |
3,933 | brute force methods note that if roots evaluates to true if roots is non-empty this is general test in pythonif evaluates to true if is non-empty or has nonzero value brute force optimization numerical algorithm we realize that xi corresponds to maximum point if yi yi similarlyxi corresponds to minimum if yi yi yi we can do this test for all "innerpoints to find all local minima and maxima in additionwe need to add an end pointi or nif the corresponding yi is global maximum or minimum implementation the algorithm above can be translated to the following python function (file brute_force_optimizer py)def brute_force_optimizer(fabn)from numpy import linspace linspace(abny (xlet maxima and minima hold the indices corresponding to (localmaxima and minima points minima [maxima [for in range( - )if [ - [ + ]maxima append(iif [ - [iy[ + ]minima append(iwhat about the end pointsy_max_inner max([ [ifor in maxima]y_min_inner min([ [ifor in minima]if [ y_max_innermaxima append( if [len( )- y_max_innermaxima append(len( )- if [ y_min_innerminima append( if [len( )- y_min_innerminima append(len( )- return and values return [( [ ] [ ]for in minima][( [ ] [ ]for in maximathe max and min functions are standard python functions for finding the maximum and minimum element of list or an object that one can iterate over with for loop |
3,934 | solving nonlinear algebraic equations an application to xd cos xlooks like def demo()from numpy import expcos minimamaxima brute_force_optimizerlambda xexp(- ** )*cos( * ) print 'minima:'minima print 'maxima:'maxima model problem for algebraic equations we shall consider the very simple problem of finding the square root of which is the positive solution of the nice feature of solving an equation whose solution is known beforehand is that we can easily investigate how the numerical method and the implementation perform in the search for the solution the xfunction corresponding to the equation is xd our interval of interest for solutions will be oe (the upper limit here is chosen somewhat arbitrarilyin the followingwe will present several efficient and accurate methods for solving nonlinear algebraic equationsboth single equation and systems of equations the methods all have in common that they search for approximate solutions the methods differhoweverin the way they perform the search for solutions the idea for the search influences the efficiency of the search and the reliability of actually finding solution for examplenewton' method is very fastbut not reliablewhile the bisection method is the slowestbut absolutely reliable no method is best at all problemsso we need different methods for different problems what is the difference between linear and nonlinear equationsyou know how to solve linear equations ax = all other types of equations xd when xis not linear function of xare called nonlinear typical way of recognizing nonlinear equation is to observe that is "not aloneas in axbut involved in product with itselfsuch as in we say that and are nonlinear terms an equation like sin cos is also nonlinear although is not explicitly multiplied by itselfbut the taylor series of sin xe and cos all involve polynomials of where is multiplied by itself newton' method newton' methodalso known as newton-raphson' methodis very famous and widely used method for solving nonlinear algebraic equations compared to the other methods we will considerit is generally the fastest one (usually by farit does not guarantee that an existing solution will be foundhowever |
3,935 | newton' method fundamental idea of numerical methods for nonlinear equations is to construct series of linear equations (since we know how to solve linear equationsand hope that the solutions of these linear equations bring us closer and closer to the solution of the nonlinear equation the idea will be clearer when we present newton' method and the secant method deriving and implementing newton' method figure shows the xfunction in our model equation numerical methods for algebraic equations require us to guess at solution first herethis guess is called the fundamental idea of newton' method is to approximate the original function xby straight linei linear functionsince it is straightforward to solve linear equations there are infinitely many choices of how to approximate xby straight line newton' method applies the tangent of xat see the rightmost tangent in fig this linear tangent function crosses the axis at point we call this is (hopefullya better approximation to the solution of xd than the next fundamental idea is to repeat this process we find the tangent of at compute where it crosses the axisat point called and repeat the process again figure shows that the process brings us closer and closer to the left it remainshoweverto see if we hit or come sufficiently close to this solution how do we compute the tangent of function xat point the tangent functionhere called fq /is linear and has two propertiesfig illustrates the idea of newton' method with xd repeatedly solving for crossing of tangent lines with the axis |
3,936 | solving nonlinear algebraic equations the slope equals to the tangent touches the xcurve at soif we write the tangent function as fq xd ax bwe must require fq and fq /resulting in fq xd the key step in newton' method is to find where the tangent crosses the axiswhich means solving fq xd fq xd this is our new candidate pointwhich we call with we get which is in accordance with the graph in fig repeating the processwe get the general scheme of newton' method may be written as xnc xn xn xn ( the computation in ( is repeated until xn is close enough to zero more preciselywe test if jf xn / with being small number we moved from to in two iterationsso it is exciting to see how fast we can approach the solution computer program can automate the calculations our first try at implementing newton' method is in function naive_newtondef naive_newton(fdfdxxeps)while abs( ( )epsx float( ( ))/dfdx(xreturn the argument is the starting valuecalled in our previous mathematical description we use float( ( )to ensure that an integer division does not happen by accident if (xand dfdx(xboth are integers for some to solve the problem we also need to implement def ( )return ** def dfdx( )return * print naive_newton(fdfdx |
3,937 | newton' method why not use an array for the approximationsnewton' method is normally formulated with an iteration index nxnc xn xn xn seeing such an indexmany would implement this as [ + [nf( [ ])/dfdx( [ ]such an array is finebut requires storage of all the approximations in large industrial applicationswhere newton' method solves millions of equations at onceone cannot afford to store all the intermediate approximations in memoryso then it is important to understand that the algorithm in newton' method has no more need for xn when xnc is computed thereforewe can work with one variable and overwrite the previous valuex ( )/dfdx(xrunning naive_newton(fdfdx eps= results in the approximate solution smaller value of eps will produce more accurate solution unfortunatelythe plain naive_newton function does not return how many iterations it usednor does it print out all the approximations :which would indeed be nice feature if we insert such printouta rerun results in we clearly see that the iterations approach the solution quickly this speed of the search for the solution is the primary strength of newton' method compared to other methods making more efficient and robust implementation the naive_newton function works fine for the example we are considering here howeverfor more general usethere are some pitfalls that should be fixed in an improved version of the code an example may illustrate what the problem islet us solve tanh xd which has solution with jx : everything works fine for examplex leads to six iterations if : |
3,938 | solving nonlinear algebraic equations - - - - adjusting slightly to gives division by zerothe approximations computed by newton' method become - - - - + the division by zero is caused by : because tanh is to machine precisionand then xd tanh / becomes zero in the denominator in newton' method the underlying problemleading to the division by zero in the above exampleis that newton' method divergesthe approximations move further and further away from if it had not been for the division by zerothe condition in the while loop would always be true and the loop would run forever divergence of newton' method occasionally happensand the remedy is to abort the method when maximum number of iterations is reached another disadvantage of the naive_newton function is that it calls the xfunction twice as many times as necessary this extra work is of no concern when xis fast to evaluatebut in large-scale industrial softwareone call to xmight take hours or daysand then removing unnecessary calls is important the solution in our function is to store the call (xin variable (f_valueand reuse the value instead of making new call (xto summarizewe want to write an improved function for implementing newton' method where we avoid division by zero allow maximum number of iterations avoid the extra evaluation of xa more robust and efficient version of the functioninserted in complete program newtons_method py for solving is listed below def newton(fdfdxxeps)f_value (xiteration_counter while abs(f_valueeps and iteration_counter tryx float(f_value)/dfdx( |
3,939 | newton' method except zerodivisionerrorprint "errorderivative zero for " sys exit( abort with error f_value (xiteration_counter + hereeither solution is foundor too many iterations if abs(f_valueepsiteration_counter - return xiteration_counter def ( )return ** def dfdx( )return * solutionno_iterations newton(fdfdxx= eps= - if no_iterations solution found print "number of function calls% ( *no_iterationsprint " solution is% (solutionelseprint "solution not found!handling of the potential division by zero is done by try-except construction python tries to run the code in the try block if anything goes wrong hereor more preciselyif python raises an exception caused by problem (such as division by zeroarray index out of boundsuse of undefined variableetc )the execution jumps immediately to the except block herethe programmer can take appropriate actions in the present casewe simply stop the program (professional programmers would avoid calling sys exit inside function insteadthey would raise new exception with an informative error messageand let the calling code have another try-except construction to stop the program the division by zero will always be detected and the program will be stopped the main purpose of our way of treating the division by zero is to give the user more informative error message and stop the program in gentler way calling sys exit with an argument different from zero (here signifies that the program stopped because of an error it is good habit to supply the value because tools in the operating system can then be used by other programs to detect that our program failed to prevent an infinite loop because of divergent iterationswe have introduced the integer variable iteration_counter to count the number of iterations in newton' method with iteration_counter we can easily extend the condition in the while such that no more iterations take place when the number of iterations reaches we could easily let this limit be an argument to the function rather than fixed constant the newton function returns the approximate solution and the number of iterations the latter equals if the convergence criterion jf / was not reached within the maximum number of iterations in the calling codewe print out the |
3,940 | solving nonlinear algebraic equations solution and the number of function calls the main cost of method for solving xd equations is usually the evaluation of xand /so the total number of calls to these functions is an interesting measure of the computational work note that in function newton there is an initial call to xand then one call to and one to in each iteration running newtons_method pywe get the following printout on the screennumber of function calls solution is as we did with the integration methods in we will collect our solvers for nonlinear algebraic equations in separate file named nonlinear_solvers py for easy import and use the first function placed in this file is then newton the newton scheme will work better if the starting value is close to the solution good starting value may often make the difference as to whether the code actually finds solution or not because of its speednewton' method is often the method of first choice for solving nonlinear algebraic equationseven if the scheme is not guaranteed to work in cases where the initial guess may be far from the solutiona good strategy is to run few iterations with the bisection method (see to narrow down the region where is close to zero and then switch to newton' method for fast convergence to the solution newton' method requires the analytical expression for the derivative xderivation of xis not always reliable process by hand if xis complicated function howeverpython has the symbolic package sympywhich we may use to create the required dfdx function in our sample problemthe recipe goes as followsfrom sympy import symbols(' 'define as mathematical symbol f_expr ** symbolic expression for (xdfdx_expr diff(f_exprxcompute '(xsymbolically turn f_expr and dfdx_expr into plain python functions lambdify([ ]argument to f_exprsymbolic expression to be evaluated dfdx lambdify([ ]dfdx_exprprint dfdx( will print the nice feature of this code snippet is that dfdx_expr is the exact analytical expression for the derivative *xif you print it out this is symbolic expression so we cannot do numerical computing with itbut the lambdify constructions turn symbolic expressions into callable python functions the next method is the secant methodwhich is usually slower than newton' methodbut it does not require an expression for /and it has only one function call per iteration |
3,941 | the secant method the secant method when finding the derivative xin newton' method is problematicor when function evaluations take too longwe may adjust the method slightly instead of using tangent lines to the graph we may use secants the approach is referred to as the secant methodand the idea is illustrated graphically in fig for our example problem the idea of the secant method is to think as in newton' methodbut instead of using xn /we approximate this derivative by finite difference or the secanti the slope of the straight line that goes through the points xn xn /and xn xn /on the graphgiven by the two most recent approximations xn and xn this slope reads xn xn ( xn xn inserting this expression for xn in newton' method simply gives us the secant methodf xn xnc xn / xn xn or xnc xn xn xn xn xn xn ( fig illustrates the use of secants in the secant method when solving oe from two chosen starting valuesx and the crossing of the corresponding secant with the axis is computedfollowed by similar computation of from and |
3,942 | solving nonlinear algebraic equations comparing ( to the graph in fig we see how two chosen starting points ( and corresponding function valuesare used to compute once we have we similarly use and to compute as with newton' methodthe procedure is repeated until xn is below some chosen limit valueor some limit on the number of iterations has been reached we use an iteration counter here toobased on the same thinking as in the implementation of newton' method we can store the approximations xn in an arraybut as in newton' methodwe notice that the computation of xnc only needs knowledge of xn and xn not "olderapproximations thereforewe can make use of only three variablesx for xnc for xn and for xn note that and must be given (guessedfor the algorithm to start program secant_method py that solves our example problem may be written asdef secant(fx eps)f_x ( f_x ( iteration_counter while abs(f_x eps and iteration_counter trydenominator float(f_x f_x )/( float(f_x )/denominator except zerodivisionerrorprint "errordenominator zero for " sys exit( abort with error f_x f_x f_x ( iteration_counter + hereeither solution is foundor too many iterations if abs(f_x epsiteration_counter - return xiteration_counter def ( )return ** solutionno_iterations secant(fx eps= - if no_iterations solution found print "number of function calls% ( no_iterationsprint " solution is% (solutionelseprint "solution not found!the number of function calls is now related to no_iterationsi the number of iterationsas no_iterationssince we need two function calls before entering the while loopand then one function call per loop iteration note thateven though we need two points on the graph to compute each updated estimateonly |
3,943 | the bisection method single function call ( ( )is required in each iteration since ( becomes the "oldf( and may simply be copied as f_x f_x (the exception is the very first iteration where two function evaluations are neededrunning secant_method pygives the following printout on the screennumber of function calls solution is as with the function newtonwe place secant in the file nonlinear_solvers py for easy import and use later the bisection method neither newton' method nor the secant method can guarantee that an existing solution will be found (see exercises and the bisection methodhoweverdoes that howeverif there are several solutions presentit finds only one of themjust as newton' method and the secant method the bisection method is slower than the other two methodsso reliability comes with cost of speed to solve oe with the bisection methodwe reason as follows the first key idea is that if xd is continuous on the interval and the function values for the interval endpoints (xl xr have opposite signsf xmust cross the axis at least once on the interval that iswe know there is at least one solution the second key idea comes from dividing the interval in two equal partsone to the left and one to the right of the midpoint xm by evaluating the sign of xm /we will immediately know whether solution must exist to the left or right of xm this is sosince if xm we know that xhas to cross the axis between xl and xm at least once (using the same argument as for the original intervallikewiseif instead xm we know that xhas to cross the axis between xm and xr at least once in any casewe may proceed with half the interval only the exception is if xm in which case solution is found such interval halving can be continued until solution is found "solutionin this caseis when jf xm / is sufficiently close to zeromore precisely (as before)jf xm / where is small number specified by the user the sketched strategy seems reasonableso let us write reusable function that can solve general algebraic equation xd (bisection_method py)def bisection(fx_lx_repsreturn_x_list=false)f_l (x_lif f_l* (x_r print "errorfunction does not have opposite signs at interval endpoints!sys exit( x_m float(x_l x_r)/ f_m (x_miteration_counter |
3,944 | solving nonlinear algebraic equations if return_x_listx_list [while abs(f_mepsif f_l*f_m same sign x_l x_m f_l f_m elsex_r x_m x_m float(x_l x_r)/ f_m (x_miteration_counter + if return_x_listx_list append(x_mif return_x_listreturn x_listiteration_counter elsereturn x_miteration_counter def ( )return ** solutionno_iterations bisection(fabeps= - print "number of function calls% ( *no_iterationsprint " solution is% (solutionnote that we first check if changes sign in oeabbecause that is requirement for the algorithm to work the algorithm also relies on continuous xfunctionbut this is very challenging for computer code to check we get the following printout to the screen when bisection_method py is runnumber of function calls solution is we notice that the number of function calls is much higher than with the previous methods required work in the bisection method if the starting interval of the bisection method is bounded by and band the solution at step is taken to be the middle valuethe error is bounded as jb aj ( because the initial interval has been halved times thereforeto meet tolerance we need iterations such that the length of the current interval equals jb aj ln /=dnd ln |
3,945 | rate of convergence this is great advantage of the bisection methodwe know beforehand how many iterations it takes to meet certain accuracy in the solution as with the two previous methodsthe function bisection is placed in the file nonlinear_solvers py for easy import and use rate of convergence with the methods abovewe noticed that the number of iterations or function calls could differ quite substantially the number of iterations needed to find solution is closely related to the rate of convergencewhich dictates the speed of error reduction as we approach the root more preciselywe introduce the error in iteration as en jx xn jand define the convergence rate as enc enq ( where is constant the exponent measures how fast the error is reduced from one iteration to the next the larger isthe faster the error goes to zeroand the fewer iterations we need to meet the stopping criterion jf / single in ( is defined in the limit for finite nand especially smaller nq will vary with to estimate qwe can compute all the errors en and set up ( for three consecutive experiments nand en en enc enq dividing these two equations by each other and solving with respect to gives qd ln enc =en ln en =en since this will vary somewhat with nwe call it qn as growswe expect qn to approach limit (qn qto compute all the qn valueswe need all the xn approximations howeverour previous implementations of newton' methodthe secant methodand the bisection method returned just the final approximation thereforewe have extended the implementations in the module file nonlinear_solvers py such that the user can choose whether the final value or the whole history of solutions is to be returned each of the extended implementations now takes an extra parameter return_x_list this parameter is booleanset to true if the function is supposed to return all the root approximationsor falseif the function should only return the final approximation as an examplelet us take closer look at newtondef newton(fdfdxxepsreturn_x_list=false)f_value (xiteration_counter if return_x_listx_list [ |
3,946 | solving nonlinear algebraic equations while abs(f_valueeps and iteration_counter tryx float(f_value)/dfdx(xexcept zerodivisionerrorprint "errorderivative zero for " sys exit( abort with error f_value (xiteration_counter + if return_x_listx_list append(xhereeither solution is foundor too many iterations if abs(f_valueepsiteration_counter - lack of convergence if return_x_listreturn x_listiteration_counter elsereturn xiteration_counter the function is found in the file nonlinear_solvers py we can now make call xiter newton(fdfdxx= eps= - return_x_list=trueand get list returned with knowledge of the exact solution of xd we can compute all the errors en and all the associated qn values with the compact function def rate(xx_exact) [abs(x_ x_exactfor x_ in xq [log( [ + ]/ [ ])/log( [ ]/ [ - ]for in range( len( )- )return the error model ( works well for newton' method and the secant method for the bisection methodhoweverit works well in the beginningbut not when the solution is approached we can compute the rates qn and print them nicelydef print_rates(methodxx_exact) [' fq_ for q_ in rate(xx_exact)print method ':for q_ in qprint q_print the result for print_rates('newton' is newton |
3,947 | solving multiple nonlinear algebraic equations indicating that is the rate for newton' method similar computation using the secant methodgives the rates secant here it seems that : is the limit remark if we in the bisection method think of the length of the current interval containing the solution as the error en then ( works perfectly since enc and but if en is the true error jx xn jit is easily seen from sketch that this error can oscillate between the current interval length and potentially very small value as we approach the exact solution the corresponding rates qn fluctuate widely and are of no interest solving multiple nonlinear algebraic equations so far in this we have considered single nonlinear algebraic equation howeversystems of such equations arise in number of applicationsforemost nonlinear ordinary and partial differential equations of the previous algorithmsonly newton' method is suitable for extension to systems of nonlinear equations abstract notation suppose we have nonlinear equationswritten in the following abstract formf xn xn :::dfn xn ( ( ( ( ( it will be convenient to introduce vector notation / xn the system can now be written as xd as specific example on the notation abovethe system cos xyx dx ( ( |
3,948 | solving nonlinear algebraic equations can be written in our abstract form by introducing and then cos xd yx taylor expansions for multi-variable functions we follow the ideas of newton' method for one equation in one variableapproximate the nonlinear by linear function and find the root of that function when variables are involvedwe need to approximate vector function xby some linear function fq cwhere is an matrix and is some vector of length the technique for approximating by linear function is to use the first two terms in taylor series expansion given the value of and its partial derivatives with respect to at some point we can approximate the value at some point by the two first term in taylor series expansion around rf the next terms in the expansions are omitted here and of size jjx jj which are assumed to be small compared with the two terms above the expression rf is the matrix of all the partial derivatives of component ij in rf is @fi @xj for examplein our system ( )-( we can use sympy to compute the jacobianfrom sympy import symbols(' ' ** *cos(pi* * exp(- **(- diff( -pi* *sin(pi* * cos(pi* diff( - diff( **(- diff( exp(- we can then write rf @ @ @ @ @ @ @ @ cos sin the matrix rf is called the jacobian of and often denoted by |
3,949 | solving multiple nonlinear algebraic equations newton' method the idea of newton' method is that we have some approximation to the root and seek new (and hopefully betterapproximation by approximating by linear function and solve the corresponding linear system of algebraic equations we approximate the nonlinear problem by the linear problem ( where is just another notation for rf the equation ( is linear system with coefficient matrix and right-hand side vector we therefore write this system in the more familiar form / /where we have introduce symbol for the unknown vector that multiplies the jacobian the -th iteration of newton' method for systems of algebraic equations consists of two steps solve the linear system / with respect to set solving systems of linear equations must make use of appropriate software gaussian elimination is the most commonand in general the most robustmethod for this purpose python' numpy package has module linalg that interfaces the well-known lapack package with high-quality and very well tested subroutines for linear algebra the statement numpy linalg solve(absolves system ax with lapack method based on gaussian elimination when nonlinear systems of algebraic equations arise from discretization of partial differential equationsthe jacobian is very often sparsei most of its elements are zero in such cases it is important to use algorithms that can take advantage of the many zeros gaussian elimination is then slow methodand (muchfaster methods are based on iterative techniques implementation here is very simple implementation of newton' method for systems of nonlinear algebraic equationsimport numpy as np def newton_system(fjxeps)""solve nonlinear system = by newton' method is the jacobian of both and must be functions of at inputx holds the start value the iteration continues until || |eps "" |
3,950 | solving nonlinear algebraic equations f_value (xf_norm np linalg norm(f_valueord= norm of vector iteration_counter while abs(f_normeps and iteration_counter delta np linalg solve( ( )-f_valuex delta f_value (xf_norm np linalg norm(f_valueord= iteration_counter + hereeither solution is foundor too many iterations if abs(f_normepsiteration_counter - return xiteration_counter we can test the function newton_system with the system ( )-( )def test_newton_system ()from numpy import cossinpiexp def ( )return np array[ [ ]** [ [ ]*cos(pi* [ ]) [ ]* [ exp(- [ ] [ ]**(- )]def ( )return np array[[ * [ cos(pi* [ ]pi* [ ]*sin(pi* [ ])- ][ [ [ ]**(- ) [ exp(- [ ])]]expected np array([ ]tol - xn newton_system(fjx=np array([ - ])eps= print nx error_norm np linalg norm(expected xord= assert error_norm tol'norm of error =%gerror_norm print 'norm of error =%gerror_norm herethe testing is based on the norm of the error vector alternativelywe could test against the values of that the algorithm findswith appropriate tolerances for exampleas chosen for the error normif eps= tolerance of can be used for [ and [ exercises exercise understand why newton' method can fail the purpose of this exercise is to understand when newton' method works and fails to this endsolve tanh by newton' method and study the intermediate details of the algorithm start with : plot the tangent in each iteration of newton' method then repeat the calculations and the plotting when : explain what you observe filenamenewton_failure |
3,951 | exercises exercise see if the secant method fails does the secant method behave better than newton' method in the problem described in exercise try the initial guesses : and : : and : and : and : filenamesecant_failure exercise understand why the bisection method cannot fail solve the same problem as in exercise using the bisection methodbut let the initial interval be oe report how the interval containing the solution evolves during the iterations filenamebisection_nonfailure exercise combine the bisection method with newton' method an attractive idea is to combine the reliability of the bisection method with the speed of newton' method such combination is implemented by running the bisection method until we have narrow intervaland then switch to newton' method for speed write function that implements this idea start with an interval oeaband switch to newton' method when the current interval in the bisection method is fraction of the initial interval ( when the interval has length /potential divergence of newton' method is still an issueso if the approximate root jumps out of the narrowed interval (where the solution is known to lie)one can switch back to the bisection method the value of must be given as an argument to the functionbut it may have default value of try the new method on tanh xd with an initial interval oe filenamebisection_newton py exercise write test function for newton' method the purpose of this function is to verify the implementation of newton' method in the newton function in the file nonlinear_solvers py construct an algebraic equation and perform two iterations of newton' method by hand or with the aid of sympy find the corresponding size of jf / and use this as value for eps when calling newton the function should then also perform two iterations and return the same approximation to the root as you calculated manually implement this idea for unit test as test function test_newton(filenametest_newton py exercise solve nonlinear equation for vibrating beam an important engineering problem that arises in lot of applications is the vibrations of clamped beam where the other end is free this problem can be analyzed analyticallybut the calculations boil down to solving the following nonlinear algebraic equationcosh cos |
3,952 | solving nonlinear algebraic equations where is related to important beam parameters through % ei where is the density of the beama is the area of the cross sectione is young' modulusand is the moment of the inertia of the cross section the most important parameter of interest is !which is the frequency of the beam we want to compute the frequencies of vibrating steel beam with rectangular cross section having width mm and height mm the density of steel is kg/ and pa the moment of inertia of rectangular cross section is bh = aplot the equation to be solved so that one can inspect where the zero crossings occur hint when writing the equation as vd the function increases its amplitude dramatically with it is therefore wise to look at an equation with damped amplitudeg vd vd plot instead bcompute the first three frequencies filenamebeam_vib py 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,953 | getting access to python this appendix describes different technologies for either installing python on your own computer or accessing python in the cloud plain python is very easy to install and use in cloud servicesbut for this book we need many add-on packages for doing scientific computations python together with these packages constitute complex software eco system that is non-trivial to buildso we strongly recommend to use one of the techniques described next required software the strictly required software packages for working with this book are python version [ numerical python (numpy[ for array computing matplotlib [ for plotting desired add-on packages are ipython [ for interactive computing scitools [ for add-ons to numpy scientificpython [ for add-ons to numpy pytest or nose for testing programs pip for installing python packages cython for compiling python to some of the text is taken from the th edition of the book primer on scientifi programming with pythonby langtangenpublished by springer (cthe author( lingeh langtangenprogramming for computations pythontexts in computational science and engineering doi -- _a |
3,954 | getting access to python sympy [ for symbolic mathematics scipy [ for advanced scientific computing python or python comes in two versionsversion and and these are not fully compatible howeverfor the programs in this bookthe differences are very smallthe major one being printwhich in python is statement like print ' :' ' :' while in python it is function call print' :' ' :'bthe authors have written python code in this book in way that makes porting to version or later trivialmost programs will just need fix of the print statement this can be automatically done by running to prog py to transform python program prog py to its python counterpart one can also use tools like future or six to easily write programs that run under both versions and or the futurize program can automatically do this for you based on code since many tools for doing scientific computing in python are still only available for python version we use this version in the present bookbut emphasize that it has to be and not older versions there are different ways to get access to python with the required packages use computer system at an institution where the software is installed such system can also be used from your local laptop through remote login over network install the software on your own laptop use web service system administrator can take the list of software packages and install the missing ones on computer system for the two other optionsdetailed descriptions are given below using web service is very straightforwardbut has the disadvantage that you are constrained by the packages that are allowed to install on the service there are services at the time of this writing that suffice for working with most of this bookbut if you are going to solve more complicated mathematical problemsyou will need more sophisticated mathematical python packagesmore storage and more computer resourcesand then you will benefit greatly from having python installed on your own computer |
3,955 | anaconda and spyder anaconda and spyder anaconda is free python distribution produced by continuum analytics and contains about python packagesas well as python itselffor doing wide range of scientific computations anaconda can be downloaded from downloads choose python version the integrated development environment (idespyder is included with anaconda and is our recommended tool for writing and running python programs on mac and windowsunless you have preference for plain text editor for writing programs and terminal window for running them spyder on mac spyder is started by typing spyder in (newterminal application if you get an error message unknown localeyou need to type the following line in the terminal applicationor preferably put the line in your $homebashrc unix initialization fileexport lang=en_us utf- export lc_all=en_us utf- installation of additional packages anaconda installs the pip tool that is handy to install additional packages in terminal application on mac or in powershell terminal on windowswrite terminal pip install --user packagename how to write and run python program you have basically three choices to develop and test python program use text editor and terminal window use an integrated development environment (ide)like spyderwhich offers window with text editor and functionality to run programs and observe the output use the ipython notebook the ipython notebook is briefly descried in sect while the other two options are outlined below |
3,956 | getting access to python the need for text editor since programs consist of plain textwe need to write this text with the help of another program that can store the text in file you have most likely extensive experience with writing text on computerbut for writing your own programs you need special programscalled editorswhich preserve exactly the characters you type the widespread word processorsmicrosoft word being primary exampleare aimed at producing nice-looking reports these programs format the text and are not acceptable tools for writing your own programseven though they can save the document in pure text format spaces are often important in python programsand editors for plain text give you complete control of the spaces and all other characters in the program file text editors the most widely used editors for writing programs are emacs and vimwhich are available on all major platforms some simpler alternatives for beginners are linuxgedit mac os xtextwrangler windowsnotepad+we may mention that python comes with an editor called idlewhich can be used to write programs on all three platformsbut running the program with commandline arguments is bit complicated for beginners in idle so idle is not my favorite recommendation gedit is standard program on linux platformsbut all other editors must be installed in your system this is easyjust google the namedownload the fileand follow the standard procedure for installation all of the mentioned editors come with graphical user interface that is intuitive to usebut the major popularity of emacs and vim is due to their rich set of short-keys so that you can avoid using the mouse and consequently edit at higher speed terminal windows to run the python programyou need terminal window this is window where you can issue unix commands in linux and mac os systems and dos commands in windows on linux computergnome-terminal is my favoritebut other choices work equally wellsuch as xterm and konsole on mac computerlaunch the application utilities terminal on windowslaunch powershell you must first move to the right folder using the cd foldername command then running python program prog py is matter of writing python prog py whatever the program prints can be seen in the terminal window |
3,957 | how to write and run python program using plain text editor and terminal window create folder where your python programs can be locatedsay with name mytest under your home folder this is most conveniently done in the terminal window since you need to use this window anyway to run the program the command for creating new folder is mkdir mytest move to the new foldercd mytest start the editor of your choice write program in the editore just the line print 'hello!save the program under the name myprog py in the mytest folder move to the terminal window and write python myprog py you should see the word hellobeing printed in the window spyder spyder is graphical application for developing and running python programsavailable on all major platforms spyder comes with anaconda and some other pre-built environments for scientific computing with python on ubuntu it is conveniently installed by sudo apt-get install spyder the left part of the spyder window contains plain text editor click in this window and write print 'hello!and return choose run from the run pulldown menuand observe the output helloin the lower right window where the output from programs is visible you may continue with more advanced statements involving graphicsimport matplotlib pyplot as plt import numpy as np np linspace( np exp(- )*np sin(np pi*xplt plot( ,yplt title('first test of spyder'plt savefig('tmp png'plt show(choosing run run now leads to separate window with plot of the function sin xfigure shows how the spyder application may look like the plot file we generate in the above programtmp pngis by default found in the spyder folder listed in the default text in the top of the program you can choose run configure to change this folder as desired the program you write is written to file temp py in the same default folderbut any name and folder can be specified in the standard file save as menu convenient feature of spyder is that the upper right window continuously displays documentation of the statements you write in the editor to the left |
3,958 | getting access to python fig the spyder integrated development environment the sagemathcloud and wakari web services you can avoid installing python on your machine completely by using web service that allows you to write and run python programs computational science projects will normally require some kind of visualization and associated graphics packageswhich is not possible unless the service offers ipython notebooks there are two excellent web services with notebookssagemathcloud at comand wakari at account before you can write notebooks in the web browser and download them to your own computer basic intro to sagemathcloud sign inclick on new projectgive title to your project and decide whether it should be private or publicclick on the project when it appears in the browserand click on create or import fileworksheetterminal or directory if your python program needs graphicsyou need to choose ipython notebookotherwise you can choose file write the name of the file above the row of buttons assuming we do not need any graphicswe create plain python filesay with name py py by clicking file you are brought to browser window with text editor where you can write python code write some code and click save to run the programclick on the plus icon (new)choose terminaland you have plain unix terminal window where you can write python py py to run the program tabs over the terminal (or editorwindow make it easy to jump between the editor and the terminal to download the fileclick on filespoint on the relevant line with the fileand download icon appears to the very right the ipython notebook option works much in the same waysee sect |
3,959 | writing ipython notebooks basic intro to wakari after having logged in at the wakari io siteyou automatically enter an ipython notebook with short introduction to how the notebook can be used click on the new notebook button to start new notebook wakari enables creating and editing plain python files tooclick on the add file icon in pane to the leftfill in the program nameand you enter an editor where you can write program pressing execute launches an ipython session in terminal windowwhere you can run the program by run prog py if prog py is the name of the program to download the fileselect test py in the left pane and click on the download file icon there is pull-down menu where you can choose what type of terminal window you wanta plain unix shellan ipython shellor an ipython shell with matplotlib for plotting using the latteryou can run plain python programs or commands with graphics just choose the type of terminal and click on +tab to make new terminal window of the chosen type installing your own python packages both sagemathcloud and wakari let you install your own python packages to install any package packagename available at pypi run terminal pip install --user packagename to install the scitools packagewhich is useful when working with this bookrun the command terminal pip install --user - git+ writing ipython notebooks the ipython notebook is splendid interactive tool for doing sciencebut it can also be used as platform for developing python code you can either run it locally on your computer or in web service like sagemathcloud or wakari installation on your computer is trivial on ubuntujust sudo apt-get install ipython-notebookand also on windows and mac by using anaconda or enthought canopy for the python installation the interface to the notebook is web browseryou write all the code and see all the results in the browser window there are excellent youtube videos on how to use the ipython notebookso here we provide very quick "step zeroto get anyone started |
3,960 | getting access to python simple program in the notebook start the ipython notebook locally by the command ipython notebook or go to sagemathcloud or wakari as described above the default input area is cell for python code type * * * ** in cell and run the cell by clicking on run selected (notebook running locally on your machineor on the "playbutton (notebook running in the cloudthis action will execute the python code and initialize the variables gv tand you can then write print in new cellexecute that celland see the output of this statement in the browser it is easy to go back to celledit the codeand re-execute it to download the notebook to your computerchoose the file download as menu and select the type of file to be downloadedthe original notebook format ipynb file extensionor plain python program version of the notebook py file extensiona mixing textmathematicscodeand graphics the real strength of ipython notebooks arises when you want to write report to document how problem can be explored and solved as teaseropen new notebookclick in the first celland choose markdown as format (notebook running locallyor switch from code to markdown in the pull-down menu (notebook in the cloudthe cell is now text field where you can write text with markdown syntax mathematics can be entered as latex code try some text with inline mathematics and an equation on separate lineplot the curve $ = ( )$where $ (xe^{- }\sin ( \pi ),\quad \in [ $execute the cell and you will see nicely typeset mathematics in the browser in the new celladd some code to plot /import numpy as np import matplotlib pyplot as plt %matplotlib inline make plots inline in the notebook np linspace( np exp(- )*np sin( *pi*xplt plot(xy' -'plt xlabel(' ')plt ylabel(' ' |
3,961 | writing ipython notebooks executing these statements results in plot in the browsersee fig it was popular to start the notebook by ipython notebook -pylab to import everything from numpy and matplotlib pyplot and make all plots inlinebut the -pylab option is now officially discouraged if you want the notebook to behave more as matlab and not use the np and plt prefixyou can instead of the first three lines above write %pylab fig example on an ipython notebook |
3,962 | baochuan introduction to numerical methods introduction_to_numerical_methods certik et al sympypython library for symbolic mathematics conte and de boor elementary numerical analysis an algorithmic approach mcgraw-hillthird edition danailap jolys kaberand postel an introduction to scientific computing springer greif and ascher first course in numerical methods computational science and engineering siam harder and numerical analysis for engineering ~dwharder/numericalanalysis scientificpython software package hunter matplotliba graphics environment computing in science engineering hunter et al matplotlibsoftware package for graphics jonest oliphantp petersonet al scipy scientific computing library for python kiusalaas numerical methods in engineering with python cambridgesecond edition langtangen doconce publishing platform langtangen primer on scientific programming with python texts in computational science and engineering springerfifth edition langtangen and ring scitoolssoftware tools for scientific computing github com/hplgit/scitools leveque finite difference methods for ordinary and partial differential equationssteady-state and time-dependent problems siam lyche and - merrien exercises in computational mathematics with matlab springer moler numerical computing with matlab siam molerhtml nakamura numerical analysis and graphic visualization with matlab prentice hallsecond edition oliphant python for scientific computing computing in science engineering |
3,963 | references oliphant et al numpy array processing package for python otto and denier an introduction to programming and numerical methods in matlab springer perez and granger ipythona system for interactive scientific computing computing in science engineering perezb grangeret al ipython software package for interactive scientific computing presss teukolskyw vetterlingand flannery numerical recipes cambridge python programming language recktenwald numerical methods with matlabimplementations and applications prentice-hall sewell the numerical solution of ordinary and partial differential equations wiley siauw and bayen an introduction to matlab programming and numerical methods for engineers academic press trefethen spectral methods in matlab siam trefethen approximation theory and approximation practice siam young and mohlenkamp introduction to numerical methods and matlab programming for engineers |
3,964 | nd-order runge-kutta method algorithm allocate argument keyword named ordinary positional array element index slice of sorting asarray (function) assert (function) assignment atan axis (plot) boolean expression false true boundary conditions brute force method bug ++ calculator cell class closure code exception re-use robust try-except colon comment commenting code compartment model composite midpoint method composite trapezoidal rule computational speed (measuring) computer program convergence rate copy crank-nicolson method debugger debugging def default demo function difference absolute backward centered forward relative differential equation first-order second-order diffusion equation discontinuous coefficient divergence doc string doconceix domain complex double integral midpoint double sum dynamical system |
3,965 | elif else emacs error asymptotic function (erf) message rounding tolerance euler pi euler' method exception handling execute ( program) exit (sys) exp math notation false fast code finite difference method finite precision (of float) flat program float floating point number (float) for loop format png fortran forward difference approximation forward euler scheme fourier series from function asarray assert call definition global handle input parameter local nested output parameter return take parameter garbage collection gauss quadrature gedit graph hardcopy (plot) heat equation heun' method hold (on/off) idle if implement ( program) implementation general specific import math matplotlib pyplot module numpy random (function) indent indexing one based zero based initial conditions input instability instruction int integer division integral analytically approximately exact numerically integration points interactive use (of python) ipython keyboard arrow up/down lambda function language computer programming laplace equation least squares method legend (plot) leibniz pi library function sympy linear algebra linear interpolation linspace list index |
3,966 | index append comprehension convert to array create delete loadtxt logistic model carrying capacity long lines (splitting of) loop double for index infinite iteration multiple nested while main program maple math mathematica mathematical modeling matlab matplotlib pyplot matrix mat tridiagonal vector product mesh points uniform method of lines midpoint method model computational differential equation mathematical module mol forward euler monte carlo integration nameerror newton starting value nonlinear algebraic equation nose (testing) notepad++ numerical scheme numpy object octave ode scalar vector operator arithmetic logical package parameter input output parentheses pde plot figure poisson equation print printf formatting printing formatted program crash execute flat input output run statement testing typing verification programming game prompt pseudo code py test python documentation installation shell zero-based indexing random (function) random walk range rate of convergence raw input read (from file) reserved words resonance return none value rk |
3,967 | root finding rounding error runge-kutta nd-order method runge-kutta-fehlberg sage (symbolic package) savetxt scalar ode scaling scheme script (and scripting) second-order ode rewritten as two first-order odes seed (random generators) simple pendulum simpson' rule simulation sir model source term spring damping of linear nonlinear oscillations spyder stability criterion stop program (ctrl+ ) str symbolic computations operations simplifications sympy syntax sys exit system of odes taylor series test block test function testing testing procedures text editor textwrangler theta rule title (plot) transpose (of matrix) trapezoidal rule tridiagonal matrix triple integral midpoint true try-exception tuple type conversion automatic unit tests unstable solutions validation variable assignment delete float global int local name str type vector vector ode vectorization verification verlet integration vim warning while loop wolframalpha write (to file) xlabel ylabel zeros index |
3,968 | ss textbooks on topics in the field of computational science and engineering will be considered they should be written for courses in cse education both graduate and undergraduate textbooks will be published in tcse multidisciplinary topics and multidisciplinary teams of authors are especially welcome ss formatonly works in english will be considered for evaluation purposesmanuscripts may be submitted in print or electronic formin the latter casepreferably as pdfor zipped ps-files authors are requested to use the latex style files available from springer atmonographselectronic material can be included if appropriate please contact the publisher ss those considering book which might be suitable for the series are strongly advised to contact the publisher or the series editors at an early stage general remarks careful preparation of manuscripts will help keep production time short and ensure satisfactory appearance of the finished book the following terms and conditions holdregarding free copies and royaltiesthe standard terms for springer mathematics textbooks hold please write to martin peters@springer com for details authors are entitled to purchase further copies of their book and other springer books for their personal useat discount of directly from springer-verlag |
3,969 | timothy barth nasa ames research center nas division moffett fieldca usa barth@nas nasa gov michael griebel institut fur numerische simulation der universitat bonn wegelerstr bonngermany griebel@ins uni-bonn de risto nieminen department of applied physics aalto university school of science and technology aaltofinland risto nieminen@aalto fi dirk roose department of computer science katholieke universiteit leuven celestijnenlaan leuven-heverleebelgium dirk roose@cs kuleuven be david keyes mathematical and computer sciences and engineering king abdullah university of science and technology box jeddah saudi arabia david keyes@kaust edu sa tamar schlick department of chemistry and courant institute of mathematical sciences new york university mercer street new yorkny usa schlick@nyu edu and editor for computational science and engineering at springermartin peters springer-verlag mathematics editorial iv tiergartenstrasse heidelberggermany martin peters@springer com department of applied physics and applied mathematics columbia university th street new yorkny usa kd @columbia edu |
3,970 | and engineering langtangencomputational partial differential equations numerical methods and diffpack programming nd edition quarteronif salerip gervasioscientific computing with matlab and octave th edition langtangenpython scripting for computational science rd edition gardnerg manduchidesign patterns for -science griebels knapekg zumbuschnumerical simulation in molecular dynamics langtangena primer on scientific programming with python th edition tveitoh langtangenb nielsenx caielements of scientific computing gustafssonfundamentals of scientific computing baderspace-filling curves larsonf bengzonthe finite element methodtheoryimplementation and applications ganderm ganderf kwokscientific computingan introduction using maple and matlab deuflhards roblitza guide to numerical modelling in systems biology holmesintroduction to scientific computing and data analysis lingeh langtangenprogramming for computations gentle introduction to numerical simulations with matlab/octave lingeh langtangenprogramming for computations gentle introduction to numerical simulations with python for further information on these books please have look at our mathematics catalogue at the following urlwww springer com/series/ monographs in computational science and engineering sundnesg linesx caib nielsenk - mardala tveitocomputing the electrical activity in the heart for further information on this bookplease have look at our mathematics catalogue at the following urlwww springer com/series/ |
3,971 | olga david andrea michael mark addie |
3,972 | preface xiii acknowledgments xv getting started introduction to python the basic elements of python objectsexpressionsand numerical types variables and assignment idle branching programs strings and input input iteration some simple numerical programs exhaustive enumeration for loops approximate solutions and bisection search few words about using floats newton-raphson functionsscopingand abstraction functions and scoping function definitions keyword arguments and default values scoping specifications recursion fibonacci numbers palindromes global variables modules files |
3,973 | structured typesmutabilityand higher-order functions tuples sequences and multiple assignment lists and mutability cloning list comprehension functions as objects stringstuplesand lists dictionaries testing and debugging testing black-box testing glass-box testing conducting tests debugging learning to debug designing the experiment when the going gets tough and when you have found "thebug exceptions and assertions handling exceptions exceptions as control flow mechanism assertions classes and object-oriented programming abstract data types and classes designing programs using abstract data types using classes to keep track of students and faculty inheritance multiple levels of inheritance the substitution principle encapsulation and information hiding generators mortgagesan extended example |
3,974 | simplistic introduction to algorithmic complexity thinking about computational complexity asymptotic notation some important complexity classes constant complexity logarithmic complexity linear complexity log-linear complexity polynomial complexity exponential complexity comparisons of complexity classes some simple algorithms and data structures search algorithms linear search and using indirection to access elements binary search and exploiting assumptions sorting algorithms merge sort exploiting functions as parameters sorting in python hash tables plotting and more about classes plotting using pylab plotting mortgagesan extended example stochastic programsprobabilityand statistics stochastic programs inferential statistics and simulation distributions normal distributions and confidence levels uniform distributions exponential and geometric distributions benford' distribution how often does the better team win hashing and collisions |
3,975 | random walks and more about data visualization the drunkard' walk biased random walks treacherous fields monte carlo simulation pascal' problem pass or don' pass using table lookup to improve performance finding some closing remarks about simulation models understanding experimental data the behavior of springs using linear regression to find fit the behavior of projectiles coefficient of determination using computational model fitting exponentially distributed data when theory is missing liesdamned liesand statistics garbage in garbage out (gigo pictures can be deceiving cum hoc ergo propter hoc statistical measures don' tell the whole story sampling bias context matters beware of extrapolation the texas sharpshooter fallacy percentages can confuse just beware knapsack and graph optimization problems knapsack problems greedy algorithms an optimal solution to the / knapsack problem |
3,976 | graph optimization problems some classic graph-theoretic problems the spread of disease and min cut shortest pathdepth-first search and breadth-first search dynamic programming fibonacci sequencesrevisited dynamic programming and the / knapsack problem dynamic programming and divide-and-conquer quick look at machine learning feature vectors distance metrics clustering types example and cluster -means clustering contrived example less contrived example wrapping up python quick reference index |
3,977 | this book is based on an mit course that has been offered twice year since the course is aimed at students with little or no prior programming experience who have desire to understand computational approaches to problem solving each yeara few of the students in the class use the course as stepping stone to more advanced computer science courses but for most of the students it will be their only computer science course because the course will be the only computer science course for most of the studentswe focus on breadth rather than depth the goal is to provide students with brief introduction to many topicsso that they will have an idea of what' possible when the time comes to think about how to use computation to accomplish goal that saidit is not "computation appreciationcourse it is challenging and rigorous course in which the students spend lot of time and effort learning to bend the computer to their will the main goal of this book is to help youthe readerbecome skillful at making productive use of computational techniques you should learn to apply computational modes of thoughts to frame problems and to guide the process of extracting information from data in computational manner the primary knowledge you will take away from this book is the art of computational problem solving the book is bit eccentric part - is an unconventional introduction to programming in python we braid together four strands of materialthe basics of programmingthe python programming languageconcepts central to understanding computationand computational problem solving techniques we cover most of python' featuresbut the emphasis is on what one can do with programming languagenot on the language itself for exampleby the end of the book has covered only small fraction of pythonbut it has already introduced the notions of exhaustive enumerationguess-and-check algorithmsbisection searchand efficient approximation algorithms we introduce features of python throughout the book similarlywe introduce aspects of programming methods throughout the book the idea is to help you learn python and how to be good programmer in the context of using computation to solve interesting problems part - is primarily about using computation to solve problems it assumes no knowledge of mathematics beyond high school algebrabut it does assume that the reader is comfortable with rigorous thinking and not intimidated by mathematical concepts it covers some of the usual topics found in an introductory texte computational complexity and simple algorithms |
3,978 | preface but the bulk of this part of the book is devoted to topics not found in most introductory textsdata visualizationprobabilistic and statistical thinkingsimulation modelsand using computation to understand data part - looks at three slightly advanced topics--optimization problemsdynamic programmingand clustering part can form the basis of self-contained course that can be taught in quarter or half semester experience suggests that it is quite comfortable to fit both parts and of this book into full-semester course when the material in part is includedthe course becomes more demanding than is comfortable for many students the book has two pervasive themessystematic problem solving and the power of abstraction when you have finished this book you should havelearned languagepythonfor expressing computationslearned systematic approach to organizingwriting and debugging medium-sized programsdeveloped an informal understanding of computational complexitydeveloped some insight into the process of moving from an ambiguous problem statement to computational formulation of method for solving the problemlearned useful set of algorithmic and problem reduction techniqueslearned how to use randomness and simulations to shed light on problems that don' easily succumb to closed-form solutionsand learned how to use computational toolsincluding simple statistical and visualization toolsto model and understand data programming is an intrinsically difficult activity just as "there is no royal road to geometry," there is no royal road to programming it is possible to deceive students into thinking that they have learned how to program by having them complete series of highly constrained "fill in the blankprogramming problems howeverthis does not prepare students for figuring out how to harness computational thinking to solve problems if you really want to learn the materialreading the book will not be enough at the very least you should try running some of the code in the book all of the code in the book can be found at versions of the course have been available on mit' opencourseware (ocwweb site since the site includes video recordings of lectures and complete set of problem sets and exams since the fall of edx and mitxhave offered an online version of this course we strongly recommend that you do the problem sets associated with one of the ocw or edx offerings this was euclid' purported responsecirca bcto king ptolemy' request for an easier way to learn mathematics |
3,979 | this book grew out of set of lecture notes that prepared while teaching an undergraduate course at mit the courseand therefore this bookbenefited from suggestions from faculty colleagues (especially eric grimsonsrinivas devadasand fredo durand)teaching assistantsand the students who took the course the process of transforming my lecture notes into book proved far more onerous than had expected fortunatelythis misguided optimism lasted long enough to keep me from giving up the encouragement of colleagues and family also helped keep me going eric grimsonchris termanand david guttag provided vital help ericwho is mit' chancellormanaged to find the time to read almost the entire book with great care he found numerous errors (including an embarrassingto menumber of technical errorsand pointed out places where necessary explanations were missing chris also read parts of the manuscript and discovered errors he also helped me battle microsoft wordwhich we eventually persuaded to do most of what we wanted david overcame his aversion to computer scienceand proofread multiple preliminary versions of this book were used in the mit course and the mitx course number of students in these courses pointed out errors one studentj cabrejaswas particularly helpful he found large number of typosand more than few technical errors like all successful professorsi owe great deal to my graduate students the photo on the back cover of this book depicts me supporting some of my current students in the labhoweverit is they who support me in addition to doing great research (and letting me take some of the credit for it)guha balakrishnanjoel brooksganeshapillai gartheebanjen gongyun liuanima singhjenna wiensand amy zhao all provided useful comments on this manuscript owe special debt of gratitude to julie sussmanp until started working with juliei had no idea how much difference an editor could make had worked with capable copy editors on previous booksand thought that was what needed for this book was wrong needed collaborator who could read the book with the eyes of studentand tell me what needed to be donewhat should be doneand what could be done if had the time and energy to do it julie buried me in "suggestionsthat were too good to ignore her combined command of both the english language and programming is quite remarkable finallythanks to my wifeolgafor pushing me to finish and for pitching in at critical times |
3,980 | computer does two thingsand two things onlyit performs calculations and it remembers the results of those calculations but it does those two things extremely well the typical computer that sits on desk or in briefcase performs billion or so calculations second it' hard to image how truly fast that is think about holding ball meter above the floorand letting it go by the time it reaches the flooryour computer could have executed over billion instructions as for memorya typical computer might have hundreds of gigabytes of storage how big is thatif byte (the number of bitstypically eightrequired to represent one characterweighed one ounce (which it doesn' ) gigabytes would weigh more than , , tons for comparisonthat' roughly the weight of all the coal produced in year in the for most of human historycomputation was limited by the speed of calculation of the human brain and the ability to record computational results with the human hand this meant that only the smallest problems could be attacked computationally even with the speed of modern computersthere are still problems that are beyond modern computational models ( understanding climate change)but more and more problems are proving amenable to computational solution it is our hope that by the time you finish this bookyou will feel comfortable bringing computational thinking to bear on solving many of the problems you encounter during your studiesworkand even everyday life what do we mean by computational thinkingall knowledge can be thought of as either declarative or imperative declarative knowledge is composed of statements of fact for example"the square root of is number such that * this is statement of fact unfortunately it doesn' tell us how to find square root imperative knowledge is "how toknowledgeor recipes for deducing information heron of alexandria was the first to document way to compute the square root of number his method can be summarized asstart with guessg if * is close enough to xstop and say that is the answer otherwise create new guess by averaging and /gi ( / )/ using this new guesswhich we again call grepeat the process until * is close enough to many believe that heron was not the inventor of this methodand indeed there is some evidence that it was well known to the ancient babylonians |
3,981 | getting started considerfor examplefinding the square root of set to some arbitrary valuee we decide that * is not close enough to set to ( / )/ we decide that * is still not close enough to set to ( )/ we decide that * is close enoughso we stop and declare to be an adequate approximation to the square root of note that the description of the method is sequence of simple stepstogether with flow of control that specifies when each step is to be executed such description is called an algorithm this algorithm is an example of guessand-check algorithm it is based on the fact that it is easy to check whether or not guess is good one bit more formallyan algorithm is finite list of instructions that describe computation that when executed on provided set of inputs will proceed through set of well-defined states and eventually produce an output an algorithm is bit like recipe from cookbook put custard mixture over heat stir dip spoon in custard remove spoon and run finger across back of spoon if clear path is leftremove custard from heat and let cool otherwise repeat it includes some tests for deciding when the process is completeas well as instructions about the order in which to execute instructionssometimes jumping to some instruction based on test so how does one capture this idea of recipe in mechanical processone way would be to design machine specifically intended to compute square roots odd as this may soundthe earliest computing machines werein factfixedprogram computersmeaning they were designed to do very specific thingsand were mostly tools to solve specific mathematical probleme to compute the trajectory of an artillery shell one of the first computers (built in by atanasoff and berrysolved systems of linear equationsbut could do nothing else alan turing' bombe machinedeveloped during world war iiwas designed strictly for the purpose of breaking german enigma codes some very simple computers still use this approach for examplea four-function calculator is fixed-program computer it can do basic arithmeticbut it cannot for simplicitywe are rounding results the word "algorithmis derived from the name of the persian mathematician muhammad ibn musa al-khwarizmi |
3,982 | be used as word processor or to run video games to change the program of such machineone has to replace the circuitry the first truly modern computer was the manchester mark it was distinguished from its predecessors by the fact that it was stored-program computer such computer stores (and manipulatesa sequence of instructionsand has set of elements that will execute any instruction in that sequence by creating an instruction-set architecture and detailing the computation as sequence of instructions ( program)we make highly flexible machine by treating those instructions in the same way as dataa stored-program machine can easily change the programand can do so under program control indeedthe heart of the computer then becomes program (called an interpreterthat can execute any legal set of instructionsand thus can be used to compute anything that one can describe using some basic set of instructions both the program and the data it manipulates reside in memory typically there is program counter that points to particular location in memoryand computation starts by executing the instruction at that point most oftenthe interpreter simply goes to the next instruction in the sequencebut not always in some casesit performs testand on the basis of that testexecution may jump to some other point in the sequence of instructions this is called flow of controland is essential to allowing us to write programs that perform complex tasks returning to the recipe metaphorgiven fixed set of ingredients good chef can make an unbounded number of tasty dishes by combining them in different ways similarlygiven small fixed set of primitive elements good programmer can produce an unbounded number of useful programs this is what makes programming such an amazing endeavor to create recipesor sequences of instructionswe need programming language in which to describe these thingsa way to give the computer its marching orders in the british mathematician alan turing described hypothetical computing device that has come to be called universal turing machine the machine had an unbounded memory in the form of tape on which one could write zeros and onesand some very simple primitive instructions for movingreadingand writing to the tape the church-turing thesis states that if function is computablea turing machine can be programmed to compute it the "ifin the church-turing thesis is important not all problems have computational solutions for exampleturing showed that it is impossible to write program that given an arbitrary programcall it pprints true if and only if will run forever this is known as the halting problem this computer was built at the university of manchesterand ran its first program in it implemented ideas previously described by john von neumann and was anticipated by the theoretical concept of the universal turing machine described by alan turing in |
3,983 | getting started the church-turing thesis leads directly to the notion of turing completeness programming language is said to be turing complete if it can be used to simulate universal turing machine all modern programming languages are turing complete as consequenceanything that can be programmed in one programming language ( pythoncan be programmed in any other programming language ( javaof coursesome things may be easier to program in particular languagebut all languages are fundamentally equal with respect to computational power fortunatelyno programmer has to build programs out of turing' primitive instructions insteadmodern programming languages offer largermore convenient set of primitives howeverthe fundamental idea of programming as the process of assembling sequence of operations remains central whatever set of primitives one hasand whatever methods one has for using themthe best thing and the worst thing about programming are the samethe computer will do exactly what you tell it to do this is good thing because it means that you can make it do all sorts of fun and useful things it is bad thing because when it doesn' do what you want it to doyou usually have nobody to blame but yourself there are hundreds of programming languages in the world there is no best language (though one could nominate some candidates for worstdifferent languages are better or worse for different kinds of applications matlabfor exampleis an excellent language for manipulating vectors and matrices is good language for writing the programs that control data networks php is good language for building web sites and python is good general-purpose language each programming language has set of primitive constructsa syntaxa static semanticsand semantics by analogy with natural languagee englishthe primitive constructs are wordsthe syntax describes which strings of words constitute well-formed sentencesthe static semantics defines which sentences are meaningfuland the semantics defines the meaning of those sentences the primitive constructs in python include literals ( the number and the string 'abc'and infix operators ( and /the syntax of language defines which strings of characters and symbols are well formed for examplein english the string "cat dog boy is not syntactically valid sentencebecause the syntax of english does not accept sentences of the form in pythonthe sequence of primitives is syntactically well formedbut the sequence is not the static semantics defines which syntactically valid strings have meaning in englishfor examplethe string " are big,is of the form <linking verbwhich is syntactically acceptable sequence neverthelessit is not valid englishbecause the noun "iis singular and the verb "areis plural this is an example of static semantic error in pythonthe sequence /'abcis syntactically well formed )but |
3,984 | produces static semantic error since it is not meaningful to divide number by string of characters the semantics of language associates meaning with each syntactically correct string of symbols that has no static semantic errors in natural languagesthe semantics of sentence can be ambiguous for examplethe sentence " cannot praise this student too highly,can be either flattering or damning programming languages are designed so that each legal program has exactly one meaning though syntax errors are the most common kind of error (especially for those learning new programming language)they are the least dangerous kind of error every serious programming language does complete job of detecting syntactic errorsand will not allow users to execute program with even one syntactic error furthermorein most cases the language system gives sufficiently clear indication of the location of the error that it is obvious what needs to be done to fix it the situation with respect to static semantic errors is bit more complex some programming languagese javado lot of static semantic checking before allowing program to be executed otherse and python (alas)do relatively less static semantic checking python does do considerable amount of static semantic checking while running program howeverit does not catch all static semantic errors when these errors are not detectedthe behavior of program is often unpredictable we will see examples of this later in the book one doesn' usually speak of program as having semantic error if program has no syntactic errors and no static semantic errorsit has meaningi it has semantics of coursethat isn' to say that it has the semantics that its creator intended it to have when program means something other than what its creator thinks it meansbad things can happen what might happen if the program has an errorand behaves in an unintended wayit might crashi stop running and produce some sort of obvious indication that it has done so in properly designed computing systemwhen program crashes it does not do damage to the overall system of coursesome very popular computer systems don' have this nice property almost everyone who uses personal computer has run program that has managed to make it necessary to restart the whole computer or it might keep runningand runningand runningand never stop if one has no idea of approximately how long the program is supposed to take to do its jobthis situation can be hard to recognize or it might run to completion and produce an answer that mightor might notbe correct |
3,985 | getting started each of these is badbut the last of them is certainly the worstwhen program appears to be doing the right thing but isn'tbad things can follow fortunes can be lostpatients can receive fatal doses of radiation therapyairplanes can crashetc whenever possibleprograms should be written in such way that when they don' work properlyit is self-evident we will discuss how to do this throughout the book finger exercisecomputers can be annoyingly literal if you don' tell them exactly what you want them to dothey are likely to do the wrong thing try writing an algorithm for driving between two destinations write it the way you would for personand then imagine what would happen if that person executed the algorithm exactly as written for examplehow many traffic tickets might they get |
3,986 | though each programming language is different (though not as different as their designers would have us believe)there are some dimensions along which they can be related low-level versus high-level refers to whether we program using instructions and data objects at the level of the machine ( move bits of data from this location to that locationor whether we program using more abstract operations ( pop up menu on the screenthat have been provided by the language designer general versus targeted to an application domain refers to whether the primitive operations of the programming language are widely applicable or are fine-tuned to domain for example adobe flash is designed to facilitate adding animation and interactivity to web pagesbut you wouldn' want to use it build stock portfolio analysis program interpreted versus compiled refers to whether the sequence of instructions written by the programmercalled source codeis executed directly (by an interpreteror whether it is first converted (by compilerinto sequence of machine-level primitive operations (in the early days of computerspeople had to write source code in language that was very close to the machine code that could be directly interpreted by the computer hardware there are advantages to both approaches it is often easier to debug programs written in languages that are designed to be interpretedbecause the interpreter can produce error messages that are easy to correlate with the source code compiled languages usually produce programs that run more quickly and use less space in this bookwe use python howeverthis book is not about python it will certainly help readers learn pythonand that' good thing what is much more importanthoweveris that careful readers will learn something about how to write programs that solve problems this skill can be transferred to any programming language python is general-purpose programming language that can be used effectively to build almost any kind of program that does not need direct access to the computer' hardware python is not optimal for programs that have high reliability constraints (because of its weak static semantic checkingor that are built and maintained by many people or over long period of time (again because of the weak static semantic checkinghoweverpython does have several advantages over many other languages it is relatively simple language that is easy to learn because python is designed to be interpretedit can provide the kind of runtime feedback that is especially helpful to novice programmers there are also large number of freely available libraries that interface to python and provide useful extended functionality several of those are used in this book |
3,987 | introduction to python now we are ready to start learning some of the basic elements of python these are common to almost all programming languages in conceptthough not necessarily in detail the reader should be forewarned that this book is by no means comprehensive introduction to python we use python as vehicle to present concepts related to computational problem solving and thinking the language is presented in dribs and drabsas needed for this ulterior purpose python features that we don' need for that purpose are not presented at all we feel comfortable about not covering the entire language because there are excellent online resources describing almost every aspect of the language when we teach the course on which this book is basedwe suggest to the students that they rely on these free online resources for python reference material python is living language since its introduction by guido von rossum in it has undergone many changes for the first decade of its lifepython was little known and little used language that changed with the arrival of python in in addition to incorporating number of important improvements to the language itselfit marked shift in the evolutionary path of the language large number of people began developing libraries that interfaced seamlessly with pythonand continuing support and development of the python ecosystem became community-based activity python was released at the end of this version of python cleaned up many of the inconsistencies in the design of the various releases of python (often referred to as python xhoweverit was not backward compatible that meant that most programs written for earlier versions of python could not be run using implementations of python the backward incompatibility presents problem for this book in our viewpython is clearly superior to python howeverat the time of this writingsome important python libraries still do not work with python we willthereforeuse python (into which many of the most important features of python have been "back ported"throughout this book the basic elements of python python programsometimes called scriptis sequence of definitions and commands these definitions are evaluated and the commands are executed by the python interpreter in something called the shell typicallya new shell is created whenever execution of program begins in most casesa window is associated with the shell we recommend that you start python shell nowand use it to try the examples contained in the remainder of the andfor that matterlater in the book as well commandoften called statementinstructs the interpreter to do something for examplethe statement print 'yankees rule!instructs the interpreter to output the string yankees ruleto the window associated with the shell |
3,988 | the sequence of commands print 'yankees rule!print 'but not in boston!print 'yankees rule,''but not in boston!causes the interpreter to produce the output yankees rulebut not in bostonyankees rulebut not in bostonnotice that two values were passed to print in the third statement the print command takes variable number of values and prints themseparated by space characterin the order in which they appear objectsexpressionsand numerical types objects are the core things that python programs manipulate every object has type that defines the kinds of things that programs can do with objects of that type types are either scalar or non-scalar scalar objects are indivisible think of them as the atoms of the language non-scalar objectsfor example stringshave internal structure python has four types of scalar objectsint is used to represent integers literals of type int are written in the way we typically denote integers ( - or or float is used to represent real numbers literals of type float always include decimal point ( or or - (it is also possible to write literals of type float using scientific notation for examplethe literal stands for * it is the same as you might wonder why this type is not called real within the computervalues of type float are stored in the computer as floating point numbers this representationwhich is used by all modern programming languageshas many advantages howeverunder some situations it causes floating point arithmetic to behave in ways that are slightly different from arithmetic on real numbers we discuss this in section bool is used to represent the boolean values true and false none is type with single value we will say more about this when we get to variables objects and operators can be combined to form expressionseach of which evaluates to an object of some type we will refer to this as the value of the expression for examplethe expression denotes the object of type intand the expression denotes the object of type float in python print is function rather than command one would therefore write print('yankees rule!''but not in boston' yesatoms are not truly indivisible howeversplitting them is not easyand doing so can have consequences that are not always desirable |
3,989 | introduction to python the =operator is used to test whether two expressions evaluate to the same valueand the !operator is used to test whether two expressions evaluate to different values the symbol is shell prompt indicating that the interpreter is expecting the user to type some python code into the shell the line below the line with the prompt is produced when the interpreter evaluates the python code entered at the promptas illustrated by the following interaction with the interpreter ! true the built-in python function type can be used to find out the type of an objecttype( type( the operators on types int and float are listed in figure + is the sum of and if and are both of type intthe result is an int if either of them is floatthe result is float - is minus if and are both of type intthe result is an int if either of them is floatthe result is float * is the product of and if and are both of type intthe result is an int if either of them is floatthe result is float // is integer division for examplethe value of // is the int and the value of // is the int the value is because integer division returns the quotient and ignores the remainder / is divided by in python when and are both of type intthe result is also an intotherwise the result is float in this bookwe will never use to divide one int by another we will use /to do that (in python the operatorthank goodnessalways returns float for examplein python the value of / is % is the remainder when the int is divided by the int it is typically pronounced " mod ,which is short for " modulo ** is raised to the power if and are both of type intthe result is an int if either of them is floatthe result is float the comparison operators are =(equal)!(not equal)(greater)>(at least)<(lessand <(at mostfigure operators on types int and float the arithmetic operators have the usual precedence for examplebinds more tightly than +so the expression + * is evaluated by first multiplying by and then adding the result to the order of evaluation can be changed by |
3,990 | using parentheses to group subexpressionse ( + )* first adds and yand then multiplies the result by the operators on type bool area and is true if both and are trueand false otherwise or is true if at least one of or is trueand false otherwise not is true if is falseand false if is true variables and assignment variables provide way to associate names with objects consider the code pi radius area pi (radius** radius it first binds the names pi and radius to different objects of type int it then binds the name area to third object of type int this is depicted in the left panel of figure figure binding of variables to objects if the program then executes radius the name radius is rebound to different object of type intas shown in the right panel of figure note that this assignment has no effect on the value to which area is bound it is still bound to the object denoted by the expression *( ** in pythona variable is just namenothing more remember this--it is important an assignment statement associates the name to the left of the symbol with the object denoted by the expression to the right of the remember this too an object can have onemore than oneor no name associated with it if you believe that the actual value of is not you're right we even demonstrate that fact in |
3,991 | introduction to python perhaps we shouldn' have said" variable is just name despite what juliet said names matter programming languages let us describe computations in way that allows machines to execute them this does not mean that only computers read programs as you will soon discoverit' not always easy to write programs that work correctly experienced programmers will confirm that they spend great deal of time reading programs in an attempt to understand why they behave as they do it is therefore of critical importance to write programs in such way that they are easy to read apt choice of variable names plays an important role in enhancing readability consider the two code fragments *( ** pi diameter area pi*(diameter** as far as python is concernedthey are not different when executedthey will do the same thing to human readerhoweverthey are quite different when we read the fragment on the leftthere is no priori reason to suspect that anything is amiss howevera quick glance at the code on the right should prompt us to be suspicious that something is wrong either the variable should have been named radius rather than diameteror diameter should have been divided by in the calculation of the area in pythonvariable names can contain uppercase and lowercase lettersdigits (but they cannot start with digit)and the special character python variable names are case-sensitive julie and julie are different names finallythere are small number of reserved words (sometimes called keywordsin python that have built-in meanings and cannot be used as variable names different versions of python have slightly different lists of reserved words the reserved words in python are andasassertbreakclasscontinuedefdelelifelseexceptexecfinallyforfromglobalifimportinislambdanotorpassprintraisereturntrywithwhileand yield another good way to enhance the readability of code is to add comments text following the symbol is not interpreted by python for exampleone might write #subtract area of square from area of circle areac pi*radius** areas side*side difference areac-areas python allows multiple assignment the statement xy binds to and to all of the expressions on the right-hand side of the assignment are evaluated before any bindings are changed this is convenient "what' in namethat which we call rose by any other name would smell as sweet |
3,992 | since it allows you to use multiple assignment to swap the bindings of two variables for examplethe code xy xy yx print ' =' print ' =' will print idle typing programs directly into the shell is highly inconvenient most programmers prefer to use some sort of text editor that is part of an integrated development environment (idein this bookwe will use idle, the ide that comes as part of the standard python installation package idle is an applicationjust like any other application on your computer start it the same way you would start any other applicatione by double-clicking on an icon idle provides text editor with syntax highlightingautocompletionand smart indentationa shell with syntax highlightingand an integrated debuggerwhich you should ignore for now when idle starts it will open shell window into which you can type python commands it will also provide you with file menu and an edit menu (as well as some other menuswhich you can safely ignore for nowthe file menu includes commands to create new editing window into which you can type python programopen file containing an existing python programand save the contents of the current editing window into file (with file extension pythe edit menu includes standard text-editing commands ( copypasteand findplus some commands specifically designed to make it easy to edit python code ( indent region and comment out region allegedlythe name python was chosen as tribute to the british comedy troupe monty python this leads one to think that the name idle is pun on eric idlea member of the troupe |
3,993 | introduction to python for complete description of idlesee branching programs the kinds of computations we have been looking at thus far are called straightline programs they execute one statement after another in the order in which they appearand stop when they run out of statements the kinds of computations we can describe with straight-line programs are not very interesting in factthey are downright boring branching programs are more interesting the simplest branching statement is conditional as depicted in figure conditional statement has three partsa testi an expression that evaluates to either true or falsea block of code that is executed if the test evaluates to trueand an optional block of code that is executed if the test evaluates to false after conditional statement is executedexecution resumes at the code following the statement figure flow chart for conditional statement in pythona conditional statement has the form if boolean expressionblock of code elseblock of code in describing the form of python statements we use italics to describe the kinds of code that could occur at that point in program for exampleboolean expression indicates that any expression that evaluates to true or false can follow the reserved word ifand block of code indicates that any sequence of python statements can follow else |
3,994 | consider the following program that prints "evenif the value of the variable is even and "oddotherwiseif % = print 'evenelseprint 'oddprint 'done with conditionalthe expression % = evaluates to true when the remainder of divided by is and false otherwise remember that =is used for comparisonsince is reserved for assignment indentation is semantically meaningful in python for exampleif the last statement in the above code were indented it would be part of the block of code associated with the elserather than with the block of code following the conditional statement python is unusual in using indentation this way most other programming languages use some sort of bracketing symbols to delineate blocks of codee encloses blocks in bracesan advantage of the python approach is that it ensures that the visual structure of program is an accurate representation of the semantic structure of that program when either the true block or the false block of conditional contains another conditionalthe conditional statements are said to be nested in the code belowthere are nested conditionals in both branches of the top-level if statement if % = if % = print 'divisible by and elseprint 'divisible by and not by elif % = print 'divisible by and not by the elif in the above code stands for "else if it is often convenient to use compound boolean expressions in the test of conditionalfor exampleif and zprint ' is leastelif zprint ' is leastelseprint ' is leastconditionals allow us to write programs that are more interesting than straightline programsbut the class of branching programs is still quite limited one way to think about the power of class of programs is in terms of how long they can take to run assume that each line of code takes one unit of time to execute if straight-line program has lines of codeit will take units of time to run what about branching program with lines of codeit might take less than units of time to runbut it cannot take moresince each line of code is executed at most once |
3,995 | introduction to python program for which the maximum running time is bounded by the length of the program is said to run in constant time this does not mean that each time it is run it executes the same number of steps it means that there exists constantksuch that the program is guaranteed to take no more than steps to run this implies that the running time does not grow with the size of the input to the program constant-time programs are quite limited in what they can do considerfor examplewriting program to tally the votes in an election it would be truly surprising if one could write program that could do this in time that was independent of the number of votes cast in factone can prove that it is impossible to do so the study of the intrinsic difficulty of problems is the topic of computational complexity we will return to this topic several times in this book fortunatelywe need only one more programming language constructiterationto be able to write programs of arbitrary complexity we get to that in section finger exercisewrite program that examines three variables--xyand -and prints the largest odd number among them if none of them are oddit should print message to that effect strings and input objects of type str are used to represent strings of characters literals of type str can be written using either single or double quotese 'abcor "abcthe literal ' denotes string of charactersnot the number one hundred twenty-three try typing the following expressions in to the python interpreter (remember that the is promptnot something that you type)' * *' + ' '+'athe operator is said to be overloadedit has different meanings depending upon the types of the objects to which it is applied for exampleit means addition when applied to two numbers and concatenation when applied to two strings the operator is also overloaded it means what you expect it to mean when its operands are both numbers when applied to an int and strit duplicates the str for examplethe expression *'johnhas the value unlike many programming languagespython has no type corresponding to character insteadit uses strings of length |
3,996 | 'johnjohnthere is logic to this just as the expression * is equivalent to + + the expression *'ais equivalent to ' '+' '+'anow try typing ' '*'aeach of these lines generates an error message the first line produces the message nameerrorname 'ais not defined because is not literal of any typethe interpreter treats it as name howeversince that name is not bound to any objectattempting to use it causes runtime error the code ' '*'aproduces the error message typeerrorcan' multiply sequence by non-int of type 'strthat type checking exists is good thing it turns careless (and sometimes subtlemistakes into errors that stop executionrather than errors that lead programs to behave in mysterious ways the type checking in python is not as strong as in some other programming languages ( javafor exampleit is pretty clear what should mean when it is used to compare two strings or two numbers but what should the value of ' berather arbitrarilythe designers of python decided that it should be falsebecause all numeric values should be less than all values of type str the designers of some other languages decided that since such expressions don' have an obvious meaningthey should generate an error message strings are one of several sequence types in python they share the following operations with all sequence types the length of string can be found using the len function for examplethe value of len('abc'is indexing can be used to extract individual characters from string in pythonall indexing is zero-based for exampletyping 'abc'[ into the interpreter will cause it to display the string 'atyping 'abc'[ will produce the error message indexerrorstring index out of range since python uses to indicate the first element of stringthe last element of string of length is accessed using the index negative numbers are used to index from the end of string for examplethe value of 'abc'[- is 'cslicing is used to extract substrings of arbitrary length if is stringthe expression [start:enddenotes the substring of that starts at index start and ends at index end- for example'abc'[ : 'bcwhy does it end at index end- rather than endso that expressions such as 'abc'[ :len('abc')have the value one might expect if the value before the colon is omittedit defaults to if the value after the colon is omittedit defaults to the length of the string consequentlythe expression 'abc'[:is semantically equivalent to the more verbose 'abc'[ :len('abc') |
3,997 | introduction to python input python has two functions (see for discussion of functions in pythonthat can be used to get input directly from userinput and raw_input each takes string as an argument and displays it as prompt in the shell it then waits for the user to type somethingfollowed by hitting the enter key for raw_inputthe input line is treated as string and becomes the value returned by the functioninput treats the typed line as python expression and infers type in this bookwe use only raw_inputwhich is less likely to lead to programs that behave in unexpected ways consider the code name raw_input('enter your name'enter your namegeorge washington print 'are you really'name'?are you really george washington print 'are you really name '?are you really george washingtonnotice that the first print statement introduces blank before the "?it does this because when print is given multiple arguments it places blank space between the values associated with the arguments the second print statement uses concatenation to produce string that does not contain the superfluous blank and passes this as the only argument to print now considern raw_input('enter an int'enter an int print type(nnotice that the variable is bound to the str ' not the int sofor examplethe value of the expression * is ' rather than the good news is that whenever string is valid literal of some typea type conversion can be applied to it type conversions (also called type castsare used often in python code we use the name of type to convert values to that type sofor examplethe value of int(' ')* is when float is converted to an intthe number is truncated (not rounded) the value of int( is the int iteration generic iteration (also called loopingmechanism is depicted in figure like conditional statement it begins with test if the test evaluates to truethe program executes the loop body onceand then goes back to reevaluate the test this process is repeated until the test evaluates to falseafter which control passes to the code following the iteration statement python has only one commandinput somewhat confusinglypython ' input has the same semantics as raw_input in python go figure |
3,998 | introduction to python figure flow chart for iteration consider the following examplesquare an integerthe hard way ans itersleft while (itersleft ! )ans ans itersleft itersleft print str( '*str(xstr(ansthe code starts by binding the variable to the integer it then proceeds to square by using repetitive addition the following table shows the value associated with each variable each time the test at the start of the loop is reached we constructed it by hand-simulating the codei we pretended to be python interpreter and executed the program using pencil and paper using pencil and paper might seem kind of quaintbut it is an excellent way to understand how program behaves test ans itersleft the fourth time the test is reachedit evaluates to false and flow of control proceeds to the print statement following the loop for what values of will this program terminateif = the initial value of itersleft will also be and the loop body will never be executed if the initial value of itersleft will be greater than and the loop body will be executed it is also possible to hand-simulate program using pen and paperor even text editor |
3,999 | introduction to python each time the loop body is executedthe value of itersleft is decreased by exactly this means that if itersleft started out greater than after some finite number of iterations of the loopitersleft = at this point the loop test evaluates to falseand control proceeds to the code following the while statement what if the value of is - something very bad happens control will enter the loopand each iteration will move itersleft farther from rather than closer to it the program will therefore continue executing the loop forever (or until something else bade an overflow erroroccurshow might we remove this flaw in the programinitializing itersleft to the absolute value of almost works the loop terminatesbut it prints negative value if the assignment statement inside the loop is also changedto ans ans+abs( )the code works properly we have now covered pretty much everything about python that we need to know to start writing interesting programs that deal with numbers and strings we now take short break from learning the language in the next we use python to solve some simple problems finger exercisewrite program that asks the user to input integersand then prints the largest odd number that was entered if no odd number was enteredit should print message to that effect |
Subsets and Splits