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 r...
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 ...
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 f...
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 ...
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 i...
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 ...
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 t...
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 ...
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 plac...
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 b...
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 bou...
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-...
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 ( )ret...
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 probl...
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 ...
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-...
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 c...
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 (se...
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 ...
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 req...
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 ...
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( /f...
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 propa...
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 exercis...
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 ...
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 ...
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 :...
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 t...
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 algeb...
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 ...
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 ot...
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 not...
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 c...
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 ro...
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 ...
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 ...
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' ...
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 problemle...
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= ep...
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...
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 graphica...
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 nu...
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 solut...
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_itera...
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 above...
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_valueep...
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 ...
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 ...
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 proble...
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...
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 ...
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 w...
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 t...
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 ' :'...
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 (i...
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 edito...
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 ne...
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 visualiz...
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 ad...
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 yo...
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...
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 an...
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...
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 ...
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 d...
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...
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 linea...
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 wor...
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 r...
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 gr...
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...
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 ...
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 al...
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 l...
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 le...
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 advance...
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 ...
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 trans...
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 holdin...
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 tha...
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 inst...
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 lan...
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 " ca...
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...
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...
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 pr...
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 ...
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 ...
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 variabl...
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 prog...
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 environ...
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 de...
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 assign...
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...
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...
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 ra...
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 fol...
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 ...