id
int64
0
25.6k
text
stringlengths
0
4.59k
3,700
outline some examples of pytorch syntax the main oo concepts pre-defined and programmer-supplied attributes function objects vs callables defining class in python how python creates an instance defining methods creating class hierarchy multiple-inheritance class hierarchies making class instance iterable purdue university new(vs init(
3,701
the syntax for defining method method defined for class must have special syntax that reserves the first parameter for the object on which the method is invoked this parameter is typically named self for instance methodsbut could be any legal python identifier in the script shown on the next slidewhen we invoke the constructor using the syntax xobj the parameter self in the call to init (is set implicitly to the instance under construction and the parameter nn to the value method may call any other method of classbut such call must always use class-qualified syntaxas shown by the definition of bar(on the next slide purdue university
3,702
defining method (contd in the definition shown belowone would think that function like baz(in the script below could be called using the syntax baz()but that does not work (we will see later how to define class method in pythonclass class xdef __init__(selfnn)self nn def getn(self)return self def foo(self,arg ,arg ,arg = )self arg arg arg def barself )self foo def baz()pass #--end of class definition ---xobj ( printxobj getn(xobj foo( , printxobj getn(xobj bar(printxobj getn( baz(purdue university the param 'selfis bound to the instance instance method instance method instance method this is not how you define class method error
3,703
method can be defined outside class it is not necessary for the body of method to be enclosed by class function object created outside class can be assigned to name inside the class the name will acquire the function object as its binding subsequentlythat name can be used in method call as if the method had been defined inside the class in the script shown on the next slidethe important thing to note is that is that the assignment to foo gives an attribute that is function object as shownthis object can then serve as an instance method purdue university
3,704
method defined outside class (contd def bar(self,arg ,arg arg = )self arg arg arg class class xfoo bar def __init__(selfnn)self nn def getn(self)return self #--end of class definition ---xobj ( printxobj getn(xobj foo printxobj getn(purdue university
3,705
only one method for given name rule when the python compiler digests method definitionit creates function binding for the name of the method for examplefor the following code fragment class xdef foo(selfarg arg )implemention_of_foo rest_of_class_x the compiler will introduce the name foo as key in the namespace dictionary for class the value entered for this key will be the function object corresponding to the body of the method definition purdue university
3,706
only one method per name rule (contd so if you examine the attribute dict after the class is compiledyou will see the following sort of entry in the namespace dictionary for 'foosince all the method names are stored as keys in the namespace dictionary and since the dictionary keys must be uniquethis implies that there can exist only one function object for given method name if after seeing the code snippet shown on the previous slidethe compiler saw another definition for method named for the same classthen regardless of the parameter structure of the functionthe new function object will replace the old for the value entry for the method name this is unlike what happens in +and java where function overloading plays an important role purdue university
3,707
method names can be usurped by data attribute names we just talked about how there can only be one method of given name in class -regardless of the number of arguments taken by the method definitions as more general case of the same propertya class can have only one attribute of given name what that means is that if class definition contains class variable of given name after method attribute of the same name has been definedthe binding stored for the name in the namespace dictionary will correspond to the definition that came later purdue university
3,708
destruction of instance objects python comes with an automatic garbage collector each object created is kept track of through reference counting each time an object is assigned to variableits reference count goes up by onesignifying the fact that there is one more variable holding reference to the object and each time variable whose referent object either goes out of scope or is changedthe reference count associated with the object is decreased by one when the reference count associated with an object goes to zeroit becomes candidate for garbage collection python provides us with del (for cleaning up beyond what is done by automatic garbage collection purdue university
3,709
encapsulation issues for classes encapsulation is one of the cornerstones of oo how does it work in pythonas opposed to oo in +and javaall of the attributes defined for class are available to all in python so the language depends on programmer coopration if software requirementssuch as those imposed by code maintenance and code extension considerationsdictate that the class and instance variables be accessed only through get and set methods python class and python instance object are so open that they can be modified after the objects are brought into existence purdue university
3,710
defining static attributes for class class definition usually includes two different kinds of attributesthose that exist on per-instance basis and those that exist on per-class basis the latter are commonly referred to as being static variable becomes static if it is declared outside of any method in class definition for method to become staticit needs the staticmethod(wrapper shown on the next slide is class with class variable (meaning static data attributenext serial num purdue university
3,711
static attributes (contd class robot class robotnext_serial_num def __init__(selfan_owner)self owner an_owner self idnum self get_next_idnum(def get_next_idnumself )new_idnum robot next_serial_num robot next_serial_num + return new_idnum def get_owner(self)return self owner def get_idnum(self)return self idnum end of class definition ----robot robot("zaphod"printrobot get_idnum( robot robot("trillian"printrobot get_idnum( robot robot("betelgeuse"printrobot get_idnum( purdue university
3,712
static methods in the old daysa static method used to be created by supplying function object to staticmethod(as its argument for exampleto make method called foo(staticwe' do the following def foo()print(''foo called''foo staticmethodfoo the function object returned by staticmethod(is static in the above examplewhen foo is subsequently called directly on the class using the function call operator '()'it is the callable object bound to foo in the last statement above that gets executed the modern approach to achieving the same effect is through the use of the staticmethod decoratoras in @staticmethod def foo()print ''foo called'purdue university
3,713
outline some examples of pytorch syntax the main oo concepts pre-defined and programmer-supplied attributes function objects vs callables defining class in python how python creates an instance defining methods creating class hierarchy multiple-inheritance class hierarchies making class instance iterable purdue university new(vs init(
3,714
extending class -using super(in method definitions method extension for the case of single-inheritance is illustrated in the employee-manager class hierarchy shown on slide note how the derived-class promote(calls the base-class promote()and how the derived-class myprint(calls the base-class myprint(as you will see laterextending methods in multiple inheritance hierarchies requires calling super(to illustratesuppose we wish for method foo(in derived class to call on foo(in ' superclasses to do part of the workclass zabcd)def fooself )do something superzselffoo(in the next couple of slideswe will first consider the case of single inheritancethat iswhen each child class has single parent class purdue university
3,715
method definitions in derived class calling superclass definition directly the next two slides show single inheritance hierarchywith employee as the base class and the manager as the derived class we want both the promote(and the myprint(methods of the derived class to call on the method of the same names in the base class to do part of the job as shown in lines (aand ( )we accomplish this by calling the methods promote(and the myprint(directly on the class name employee purdue university
3,716
calling superclass method definition directly base class employee class employeedef __init__(selfnampos)self name nam self position pos promotion_table 'shop_floor'staff''staff'manager''manager'executuvedef promote(self)self position employee promotion_table[self positiondef myprint(self)printself name"%sself positionend="derived class manager class manageremployee )def __init__(selfnamposdept)employee __init__(self,nam,posself dept dept def promote(self)#this promote(calls parent' promote(for part of the work if self position ='executive'print"not possiblereturn employee promoteself #(adef myprint(self)employee myprint(selfprintself dept purdue university #this print(calls parent' print(for part of the work #(
3,717
calling superclass method definition directly (contd (continued from previous slidetest code emp employee("orpheus""staff"emp myprint(orpheus staff emp promote(printemp position manager emp myprint(orpheus manager man manager("zaphod""manager""sales"man myprint(man promote(printman position executive print(isinstance(manemployee)print(isinstance(empmanager)print(isinstance(manobject)print(isinstance(empobject)true false true true purdue university zaphod manager sales
3,718
method definition in derived class calling super(for the parent class' method shown on the next slide is the same class single-inheritance class hierarchy you saw on the previous slides and the methods of the derived class still want part of the job to be done by the methods of the parent class but now the methods of the derived class invoke the built-in super(for calling on the methods of the parent class purdue university
3,719
method definition in derived class calling super(for the parent class' method (contd base class employee class employeedef __init__(selfnampos)self name nam self position pos promotion_table 'shop_floor'staff''staff'manager''manager'executuvedef promote(self)self position employee promotion_table[self positiondef myprint(self)printself name"%sself positionend="derived class manager class manageremployee )def __init__(selfnamposdept)employee __init__(self,nam,posself dept dept def promote(self)if self position ='executive'print"not possiblereturn super(managerselfpromote(def myprint(self)super(managerselfmyprint(printself dept purdue university #( #(
3,720
derived class constructor calling base class' constructor directly the point of this slide is to emphasize what you might have noticed already in the employee-manager class hierarchythe first thing that the constructor of derived class must do is to call on the constructor of the base class for the initializations that are in the latter' init (in the code shown on the next slidethis call is made in line (aas you can seethe derived class is calling init (directly on the name of the base class purdue university
3,721
derived class constructor calls base class constructor directly (contd base class employee class employeedef __init__(selfnampos)self name nam self position pos promotion_table 'shop_floor'staff''staff'manager''manager'executuvedef promote(self)self position employee promotion_table[self positiondef myprint(self)printself name"%sself positionend="derived class manager class manageremployee )def __init__(selfnamposdept)employee __init__(selfnamposself dept dept #(adef promote(self)if self position ='executive'print"not possiblereturn super(managerselfpromote(def myprint(self)super(managerselfmyprint(printself dept test code emp employee("orpheus""staff"emp myprint(orpheus staff print("\ "emp promote(printemp position manager emp myprint(orpheus manager man manager("zaphod""manager""sales"man myprint(zaphod manager sales man promote(print("\ "printman position executive print(isinstance(manemployee)print(isinstance(empmanager)print(isinstance(manobject)print(isinstance(empobject)purdue university true false true true
3,722
derived class constructor calling base class constructor through super(as shown on the next slideanother way for derived class constructor to call on the constructor of the base class is using the built-in super(as shown on the next slide note in line (athe following syntax for the call to super()super(managerself__init__(nam,posthe call to super(must mention the name of the derived class in which super(is called purdue university
3,723
derived class constructor calling base class constructor through super((contd base class employee class employeedef __init__(selfnampos)self name nam self position pos promotion_table 'shop_floor'staff''staff'manager''manager'executuvedef promote(self)self position employee promotion_table[self positiondef myprint(self)printself name"%sself positionend="derived class manager class manageremployee )def __init__(selfnamposdept)super(managerself__init__(nam,posself dept dept #(adef promote(self)if self position ='executive'print"not possiblereturn super(managerselfpromote(def myprint(self)super(managerselfmyprint(printself dept test code emp employee("orpheus""staff"emp myprint(orpheus staff print("\ "emp promote(printemp position manager emp myprint(orpheus manager man manager("zaphod""manager""sales"man myprint(zaphod manager sales man promote(print("\ "printman position executive print(isinstance(manemployee)print(isinstance(empmanager)print(isinstance(manobject)print(isinstance(empobject)purdue university true false true true
3,724
new style syntax for calling super(in derived-class constructor howeverpython allows derived class' constructor to call super(without using the derived class' name as its argument shown on the next slide is the same hierarchy that you saw on the previous slidebut with the following new-style syntax for the call to super(in line ( )super(__init__(nampospurdue university
3,725
new style syntax for calling super(in derived-class constructor (contd base class employee class employeedef __init__(selfnampos)self name nam self position pos promotion_table 'shop_floor'staff''staff'manager''manager'executuvedef promote(self)self position employee promotion_table[self positiondef myprint(self)printself name"%sself positionend="derived class manager class manageremployee )def __init__(selfnamposdept)super(__init__(namposself dept dept #(adef promote(self)if self position ='executive'print"not possiblereturn super(managerselfpromote(def myprint(self)super(managerselfmyprint(printself dept test code emp employee("orpheus""staff"emp myprint(orpheus staff print("\ "emp promote(printemp position manager emp myprint(orpheus manager print(man manager("zaphod""manager""sales"man myprint(zaphod manager sales man promote(print("\ "printman position executive print(isinstance(manemployee)print(isinstance(empmanager)print(isinstance(manobject)print(isinstance(empobject)purdue university true false true true
3,726
outline some examples of pytorch syntax the main oo concepts pre-defined and programmer-supplied attributes function objects vs callables defining class in python how python creates an instance defining methods creating class hierarchy multiple-inheritance class hierarchies making class instance iterable purdue university new(vs init(
3,727
an example of diamond inheritance python allows class to be derived from multiple base classes in generalthe header of such derived class would look like class derived_classbase base base )body of the derived class the example shown on the next slide contains diamond hierarchy for illustrating multiple inheritance the class inherits from two parentsb and both those classes inherit from athus forming an example of diamond inheritance such hierarchies lead to following questionssuppose we invoke method on derived-class instance and the method is not defined directly in the derived classin what order will the base classes be searched for an implementation of the methodthe order in which the class and its bases are searched for the implementation code is commonly referred to as the method resolution order (mroin python purdue university
3,728
an example of diamond inheritance (contd classes of abcd of the hierarchy class (object)def __init__(self)print("called ' init"class ba )def __init__(self)print("called ' init"super(__init__(class ca )def __init__(self)print("called ' init"super(__init__(class ( , )def __init__(self)print("called ' init"super(__init__(test code dobj (called ' init called ' init called ' init called ' init print( __mro__(< purdue university
3,729
on the importance of using super(in init (in order to illustrate the importance of using super() will present good-practice and bad-practice scenarios when defining multiple-inheritance hierarchy the example shown on the previous slide represented good-practice scenario in which we called the parent class' in the definition of super (for all the derived classes init (to see why what the programmer of the abc-hierarchy did on the previous slide amounted to good practicelet' say that client of the original abc hierarchy decides to extend that hierarchy because he/she wants to endow the original classes and with additional behavior that is defined in the class mixin defined on the next slide the "mixed-inversions of the original classes and are called and qrespectively purdue university
3,730
importance of using super(in classes of abc of the original hierarchy class (object)def __init__(self)print("called ' init"init ((contd class ba )def __init__(self)print("called ' init"super( ,self__init__(class ca )def __init__(self)print("called ' init"super( ,self__init__( client wants to mixin additional behaviors with the classes and --class mixin( )def __init__(self)print("called mixin' init"super(mixinself__init__(class (bmixin)def __init__(self)print("called ' init"super(pself__init__(class (cmixin)def __init__(self)print("called ' init"super(qself__init__(test code print("\np pobj (instance being constructed:\ "print("\nq qobj (instance being constructed:\ "called ' init called ' init called mixin' init called ' init called ' init called ' init called mixin' init called ' init print( __mro__(print( __mro__(purdue university
3,731
new-style version of the good-practice example of using super in init (the example shown on the next slide is basically the same as what was shown in the previous slidea good-practice scenario in which the original programmer of the abc hierarchy has used the new-style super(to call the parent class' init (in the init (for all the derived classes the only difference from the previous example is that the calls like super( ,self__init__(in the init (of the derived classes have been replaced by the more compact super(__init__(as resultwhen client of the abc-hierarchy decides to extend the original hierarchy in order to create mixin versions of those classes as shown in the part of the code that begins with the class definition for theuniversity mixin classthere is no problem purdue
3,732
new-style version of the good practice example (contd classes abc of the orignal hierarchy class (object)def __init__(self)print("called ' init"class ba )def __init__(self)print("called ' init"super(__init__(class ca )def __init__(self)print("called ' init"super(__init__(the mixin class and the mixin versions of the and classes ----class mixin( )def __init__(self)print("called mixin' init"super(__init__(class (bmixin)def __init__(self)print("called ' init"super(__init__(class (cmixin)def __init__(self)print("called ' init"super(__init__(test code print("\np pobj (instance being constructed:\ "print("\nq qobj (instance being constructed:\ "called ' init called ' init called mixin' init called ' init called ' init called ' init called mixin' init called ' init print( __mro__(print( __mro__(purdue university
3,733
consequences of not using super(what' shown on the next slide represents bad-practice scenario in which the original programmer has explicitly called the parent class' init (in the definition of init (for the derived class subsequentlya client of the abcd hierarchy decides to extend the abc hierarchy because he/she wants to endow the original classes and with additional behavior that is defined in the class mixin as defined below the "mixed-inversions of the original classes and are called and qrespectively as shown in the "testsectionwhile ' constructor calls mixin' constructoras it shouldp' constructor fails to do so purdue university
3,734
consequences of not using super()(contd classes of abc of the hierarchy class (object)def __init__(self)print("called ' init"class ba )def __init__(self)print("called ' init" __init__(selfclass ca )def __init__(self)print("called ' init"super( ,self__init__(class ( , )def __init__(self)print("called ' init"super( ,self__init__(user classes mixinpq class mixin( )def __init__(self)print("called mixin' init"super(mixinself__init__(class (bmixin)def __init__(self)print("called ' init"super(pself__init__(class (cmixin)def __init__(self)print("called ' init"super(qself__init__(test code print("\np instance being constructed:\ "pobj (#this constructor call fails to call the mixin constructor called ' init called ' init called ' init print("\nq qobj (instance being constructed:\ "called ' init called ' init called mixin' init called ' init print( __mro__(print( __mro__(purdue university
3,735
outline some examples of pytorch syntax the main oo concepts pre-defined and programmer-supplied attributes function objects vs callables defining class in python how python creates an instance defining methods creating class hierarchy multiple-inheritance class hierarchies making class instance iterable purdue university new(vs init(
3,736
iterable vs iterator class instance is iterable if you can loop over the data stored in the instance the data may be stored in the different attributes and in ways not directly accessible bysayarray like indexing class must provide for an iterator in order for its instances to be iterable and this iterable must be returned by the definition of iter for the class commonlythe iterator defined for class will itself be class that provides implementation for method named next in python and next in python purdue university
3,737
computingin the sense of doing mathematical calculationsis skill that mankind has developed over thousands of years programmingon the other handis in its infancywith history that spans few decades only both topics are vastly comprehensive and usually taught as separate subjects in educational institutions around the worldespecially at the undergraduate level this book is about the combination of the twobecause computing today becomes so much more powerful when combined with programming most universities and colleges implicitly require students to specialize in computer science if they want to learn the craft of programmingsince other student programs usually do not offer programming to an extent demanded for really mastering this craft common arguments claim that it is sufficient with brief introductionthat there is not enough room for learning programming in addition to all other must-have subjectsand that there is so much software available that few really need to program themselves consequence is that engineering students often graduate with shallow knowledge about programmingunless they happened to choose the computer science direction we think this is an unfortunate situation there is no doubt that practicing engineers and scientists need to know their pen and paper mathematics they must also be able to run off-the-shelf software for important standard tasks and will certainly do that lot neverthelessthe benefits of mastering programming are many why learn programming ready-made software is limited to handling certain standard problems what do you do when the problem at hand is not covered by the software you boughtfortunatelya lot of modern software systems are extensible via programming in factmany systems demand parts of the problem specification ( material modelsto be specified by computer code with programming skillsyou may extend the flexibility of existing software packages by combining them for exampleyou may integrate packages that do not speak to each other from the outset this makes the work flow simplermore efficientand more reliableand it puts you in position to attack new problems
3,738
preface it is easy to use excellent ready-made software the wrong way insight in programming and the mathematics behind is fundamental for understanding complex softwareavoiding pitfallsand become safe user bugs (errors in computer codeare present in most larger computer programs (also in the ones from the shop!what do you do when your ready-made software gives unexpected resultsis it bugis it wrong useor is it the mathematically correct resultexperience with programming of mathematics gives you good background for answering these questions the one who can programcan also make tailored code for simplified problem setting and use that to verify the computations done with off-the-shelf software lots of skilled people around the world solve computational problems by writing their own code and offer their code for free on the internet to take advantage of this truly great source of software in reliable wayone must normally be able to understand and possibly modify computer code offered by others it is recognized world wide that students struggle with mathematics and physics too many find such subjects difficult and boring with programmingwe can execute the good old subjects in brand new wayaccording to the authorsown experiencestudents find it much more motivating and enlightening when programming is made an integrated part of mathematics and physical science courses in particularthe problem being solved can be much more realistic than when the mathematics is restricted to what you can do with pen and paper finallywe launch our most important argument for learning computer programmingthe algorithmic thinking that comes with the process of writing program for computational problem enforces thorough understanding of both the problem and solution method we can simply quote the famous norwegian computer scientist kristen nyggaard"programming is understandingin the authorsexperienceprogramming is an excellent pedagogical tool for understanding mathematics"you think you know when you can learnare more sure when you can writeeven more when you can teachbut certain when you can program(alan perliscomputer scientist - considerfor exampleintegration numerical method for integration has much stronger focus on what the integral actually is and means compared to analytical methodswhere much time and effort must be devoted to integration by partsintegration by substitutionetc moreoverwhen programming the numerical integration formulait becomes evident that it works for "allmathematical functions and that the implementation should be in terms of general function applicable to "allintegrals in this waystudents learn to recognize special problem as belonging to class of problems ( integrationdifferential equationsroot finding)for which we have general numerical methods implemented in widely applicable software when they write this softwareas we do in this bookthey learn how to generalize and increase the abstraction level of the mathematical problem when they use this softwarethey learn how special case should be attacked by general methods and software for the class of problems that comprises the special case at hand this is the power of mathematics in nutshelland it is paramount that students understand this way of thinking
3,739
vii target audience and background knowledge this book was written for studentsteachersengineers and scientists that know nothing about programming and numerical methods from beforebut who seek minimum of the fundamental skills required to get started with programming as tool for solving scientific and engineering problems some knowledge of oneand multi-variable calculus is assumed the basic programming concepts are presented in only pages and )before practical applications of these concepts are demonstrated in important mathematical subjects addressed in the remaining parts of the book - each is followed by set of exercises that cover wide range of application arease biologygeologystatisticsphysics and mathematics the exercises were particularly designed to bring across important points from the text the reader will realize that the modest content of the first pages can in fact bring you quite far in powerful problem solvinglearning the very basics of programming should not take longbut as with any other craftmastering the skill requires continued and extensive practice some beginning practice is gained through - but the authors strongly emphasize that this is only start students should continue to practice programming in subsequent courseswhile those who exercise self-studyshould keep up the learning process through continued application of the craft the book is good starting point when teaching computer programming as an integrated part of standard university courses in mathematics and physical sciences in our experiencesuch an integration is doable and indeed rewarding numerical methods an overall goal with this book is to motivate computer programming as very powerful tool for doing mathematics all examples are related to mathematics and its use in engineering and science howeverto solve mathematical problems through computer programmingwe need numerical methods explaining basic numerical methods is therefore an integral part of the book our choice of topics is governed by what is most needed in science and engineeringas well as in the teaching of applied physical science courses mathematical models are then centralwith differential equations constituting the most frequent type of models consequentlythe numerical focus in this book is on differential equations as soft pedagogical starter for the programming of mathematicswe have chosen the topic of numerical integration there is also on root findingwhich is important for the numerical solution on nonlinear differential equations we remark that the book is deliberately brief on numerical methods this is because our focus is on implementing numerical algorithmsbut to develop reliableworking programsthe programmer must be confident about the basic ideas of the numerical approximations involved the computer languagepython we have chosen to use the programming language pythonbecause this language gives very compact and readable code that closely resembles the mathematical recipe for solving the problem at hand python also has gentle learning curve there is matlab/octave companion of this book in case that language is preferred comparing these two versions of the book provides an excellent demonstration of how similar these languages are other computer languageslike fortrancand ++have strong position in science and engineering during the last two decadeshoweverthere has been significant
3,740
preface shift in popularity from these compiled languages to more high-level and easier-toread languages like matlabpythonrmaplemathematicaand idlfor instance this latter class of languages is computationally less efficientbut superior with respect to overall human problem solving efficiency this book emphasizes how to think like programmerrather than focusing on technical language details thusthe book should put the reader in good position for learning other programming languages laterincluding the classic onesfortrancand +how this book is different there are numerous texts on computer programming and numerical methodsso how does the present one differ from the existing literaturecompared to books on numerical methodsour book has much stronger emphasis on the craft of programming and on verification we want to give students thorough understanding of how one thinks about programming as problem solving method and how one can be sure that programs are correct (wellyou can never be completely surebut we show how you can provide convincing evidence for correctnesseven though there are lots of books on numerical methods where many algorithms have corresponding computer implementation (seee [ - - the latter two are the only texts we know that apply python)it is assumed that the reader "can programbeforehand the present book teaches the craft of structured programming along with the fundamental ideas of numerical methods furthermorewe have so far not found any other numerical methods book that has strong emphasis on verifying implementations in this bookunit testing and corresponding test functions are introduced early on we also put much emphasis on coding algorithms as functionsas opposed to "flat programs"which often dominate in the literature and among practitioners functions are reusable because they utilize the general formulation of mathematical algorithm such that it becomes applicable to large class of problems there are also numerous books on computer programmingbut to our knowledge only one [ that aims to teach how to think about programming in the context of numerical methods and scientific applications that book [ has its primary focus on teaching python and is very comprehensive introduction to python as language and the thinking about programming as computer scientist sometimes one needs text that does not go so deep into the language-specific detailsbut instead targets the shortest path to reliable mathematical problem solving through programming with this attitude in minda lot of topics were left out of the present booksimply because they were not strictly needed in the mathematical problem solving process examples of such topics are object-oriented programming and python dictionaries (of which the latter omission is possibly subject to more debateif you find the present book too shallow[ might be the right choice for you that source should also work nicely as more in-depth successor of the present text whenever the need for structured introduction to programming arises in science and engineering coursesthis book may be your optioneither for self-study or for use in organized teaching the thinkinghabitsand practice covered in couple of hundred pages will put readers in firm position for utilizing and understanding the power of computers for problem solving in science and engineering
3,741
ix supplementary materials all program and data files referred to in this book are available from the book' primary web siteacknowledgments first of allwe want to thank all students who attended the courses fm modelling and simulation of dynamic systemsfm scientific computingfb mathematics and fb physics at the university college of southeast norway over the last couple of years they worked their way through early versions of this text and gave us constructive and positive feedback that helped us correct errors and improve the book in so many ways special acknowledgement goes to guandong kou and edirisinghe manjula for their careful reading of the manuscript and constructive suggestions for improvement the careful proof reading by yapi donatien achou is also highly appreciated we thank all our good colleagues at the university college of southeast norwayuniversity of osloand simula research laboratory for their continued support and interestenlightening discussionsand for providing such an inspiring environment for teaching and science in particularsvein linge is thankful to marius lysaker for their fruitful collaboration on introducing programming as an integral part of mathematics and physics bachelor courses at the university college of southeast norway finallythe authors must thank the springer team with dr martin petersthanh-ha le thiand yvonne schlatter for the effective editorial and production process the text was written in the doconce [ markup languagewhich allowed us to work with single text source for both the python and the matlab version of this bookand to produce various electronic versions of the book december svein linge and hans petter langtangen
3,742
the first few steps what is programand what is programming python program with variables the program dissection of the program why not just use pocket calculatorwhy you must use text editor to write programs installation of python write and run your first program python program with library function python program with vectorization and plotting more basic concepts using python interactively arithmeticsparentheses and rounding errors variables and objects integer division formatting text and numbers arrays plotting error messages and warnings input data symbolic computations concluding remarks exercises basic constructions if testscolon and indentation functions for loops while loops lists and tuples alternatives to arrays reading from and writing to files exercises xi
3,743
contents computing integrals basic ideas of numerical integration the composite trapezoidal rule the general formula implementation making module alternative flat special-purpose implementation the composite midpoint method the general formula implementation comparing the trapezoidal and the midpoint methods testing problems with brief testing procedures proper test procedures finite precision of floating-point numbers constructing unit tests and writing test functions vectorization measuring computational speed double and triple integrals the midpoint rule for double integral the midpoint rule for triple integral monte carlo integration for complex-shaped domains exercises solving ordinary differential equations population growth derivation of the model numerical solution programming the forward euler schemethe special case understanding the forward euler method programming the forward euler schemethe general case making the population growth model more realistic verificationexact linear solution of the discrete equations spreading of diseases spreading of flu forward euler method for the differential equation system programming the numerical methodthe special case outbreak or not abstract problem and notation programming the numerical methodthe general case time-restricted immunity incorporating vaccination discontinuous coefficientsa vaccination campaign oscillating one-dimensional systems derivation of simple model numerical solution programming the numerical methodthe special case
3,744
xiii magic fix of the numerical method the nd-order runge-kutta method (or heun' method software for solving odes the th-order runge-kutta method more effectsdampingnonlinearityand external forces illustration of linear damping illustration of linear damping with sinusoidal excitation spring-mass system with sliding friction finite difference methodundampedlinear case finite difference methodlinear damping exercises solving partial differential equations finite difference methods reduction of pde to system of odes construction of test problem with known discrete solution implementationforward euler method applicationheat conduction in rod vectorization using odespy to solve the system of odes implicit methods exercises solving nonlinear algebraic equations brute force methods brute force root finding brute force optimization model problem for algebraic equations newton' method deriving and implementing newton' method making more efficient and robust implementation the secant method the bisection method rate of convergence solving multiple nonlinear algebraic equations abstract notation taylor expansions for multi-variable functions newton' method implementation exercises getting access to python required software anaconda and spyder spyder on mac installation of additional packages how to write and run python program
3,745
contents the need for text editor text editors terminal windows using plain text editor and terminal window spyder the sagemathcloud and wakari web services basic intro to sagemathcloud basic intro to wakari installing your own python packages writing ipython notebooks simple program in the notebook mixing textmathematicscodeand graphics references index
3,746
exercise error messages exercise volume of cube exercise area and circumference of circle exercise volumes of three cubes exercise average of integers exercise interactive computing of volume and area exercise peculiar results from division exercise update variable at command prompt exercise formatted print to screen exercise python documentation and random numbers exercise errors with colonindentetc exercise compare integers and exercise functions for circumference and area of circle exercise function for area of rectangle exercise area of polygon exercise average of integers exercise while loop with errors exercise area of rectangle versus circle exercise find crossing points of two graphs exercise sort array with numbers exercise compute exercise compute combinations of sets exercise frequency of random numbers exercise game exercise linear interpolation exercise test straight line requirement exercise fit straight line to data exercise fit sines to straight line exercise count occurrences of string in string exercise hand calculations for the trapezoidal method exercise hand calculations for the midpoint method exercise compute simple integral exercise hand-calculations with sine integrals exercise make test functions for the midpoint method xv
3,747
list of exercises exercise explore rounding errors with large numbers exercise write test functions for xdx exercise rectangle methods exercise adaptive integration exercise integrating raised to exercise integrate products of sine functions exercise revisit fit of sines to function exercise derive the trapezoidal rule for double integral exercise compute the area of triangle by monte carlo integration exercise geometric construction of the forward euler method exercise make test functions for the forward euler method exercise implement and evaluate heun' method exercise find an appropriate time steplogistic model exercise find an appropriate time stepsir model exercise model an adaptive vaccination campaign exercise make sirv model with time-limited effect of vaccination exercise refactor flat program exercise simulate oscillations by general ode solver exercise compute the energy in oscillations exercise use backward euler scheme for population growth exercise use crank-nicolson scheme for population growth exercise understand finite differences via taylor series exercise use backward euler scheme for oscillations exercise use heun' method for the sir model exercise use odespy to solve simple ode exercise set up backward euler scheme for oscillations exercise set up forward euler scheme for nonlinear and damped oscillations exercise discretize an initial condition exercise simulate diffusion equation by hand exercise compute temperature variations in the ground exercise compare implicit methods exercise explore adaptive and implicit methods exercise investigate the rule exercise compute the diffusion of gaussian peak exercise vectorize function for computing the area of polygon exercise explore symmetry exercise compute solutions as exercise solve two-point boundary value problem exercise understand why newton' method can fail exercise see if the secant method fails exercise understand why the bisection method cannot fail exercise combine the bisection method with newton' method exercise write test function for newton' method exercise solve nonlinear equation for vibrating beam
3,748
the first few steps what is programand what is programmingtodaymost people are experienced with computer programstypically programs such as wordexcelpowerpointinternet explorerand photoshop the interaction with such programs is usually quite simple and intuitiveyou click on buttonspull down menus and select operationsdrag visual elements into locationsand so forth the possible operations you can do in these programs can be combined in seemingly an infinite number of waysonly limited by your creativity and imagination neverthelessprograms often make us frustrated when they cannot do what we wish one typical situation might be the following say you have some measurements from deviceand the data are stored in file with specific format you (cthe author( lingeh langtangenprogramming for computations pythontexts in computational science and engineering doi --
3,749
the first few steps may want to analyze these data in excel and make some graphics out of it howeverassume there is no menu in excel that allows you to import data in this specific format excel can work with many different data formatsbut not this one you start searching for alternatives to excel that can do the same and read this type of data files maybe you cannot find any ready-made program directly applicable you have reached the point where knowing how to write programs on your own would be of great help to youwith some programming skillsyou may write your own little program which can translate one data format to another with that little piece of tailored codeyour data may be read and analyzedperhaps in excelor perhaps by new program tailored to the computations that the measurement data demand the real power of computers can only be utilized if you can program them by programming you can get the computer to do (most often!exactly what you want programming consists of writing set of instructions in very specialized language that has adopted words and expressions from english such languages are known as programming or computer languages the set of instructions is given to program which can translate the meaning of the instructions into real actions inside the computer the purpose of this book is to teach you to write such instructions dedicated to solve mathematical and engineering problems by fundamental numerical methods there are numerous computer languages for different purposes within the engineering areathe most widely used computer languages are pythonmatlaboctavefortrancc++and to some extent mapleand mathematica how you write the instructions ( the syntaxdiffers between the languages let us use an analogy assume you are an international kind of personhaving friends abroad in englandrussia and china they want to try your favorite cake what can you dowellyou may write down the recipe in those three languages and send them over nowif you have been able to think correctly when writing down the recipeand you have written the explanations according to the rules in each languageeach of your friends will produce the same cake your recipe is the "computer program"while englishrussian and chinese represent the "computer languageswith their own rules of how to write things the end productthoughis still the same cake note that you may unintentionally introduce errors in your "recipedepending on the errorthis may cause "baking executionto stopor perhaps produce the wrong cake in your computer programthe errors you introduce are called bugs (yessmall insectsfor historical reasons)and the process of fixing them is called debugging when you try to run your program that contains errorsyou usually get warnings or error messages howeverthe response you get depends on the error and the programming language you may even get no responsebut simply the wrong "cakenote that the rules of programming language have to be followed very strictly this differs from languages like english etc where the meaning might be understood even with spelling errors and "slangincluded this book comes in two versionsone that is based on pythonand one based on matlab both python and matlab represent excellent programming environments for scientific and engineering tasks the version you are reading nowis the python version some of python' strong properties deserve mention heremany global functions can be placed in only one filefunctions are straightforwardly transferred as
3,750
arguments to other functionsthere is good support for interfacing cc+and fortran code ( python program may use code written in other languages)and functions explicitly written for scalar input often work fine (without modificationalso with vector input another important thingis that python is available for free it can be downloaded from the internet and will run on most platforms readers who want to expand their scientific programming skills beyond the introductory level of the present expositionare encouraged to study the book primer on scientific programming with python [ this comprehensive book is as suitable for beginners as for professional programmersand teaches the art of programming through huge collection of dedicated examples this book is considered the primary referenceand natural extensionof the programming matters in the present book some computer science terms note thatquite oftenthe terms script and scripting are used as synonyms for program and programmingrespectively the inventor of the perl programming languagelarry walltried to explain the difference between script and program in humorous way (from perl com )suppose you went back to ada lovelace and asked her the difference between script and program she' probably look at you funnythen say something likewella script is what you give the actorsbut program is what you give the audience that ada was one sharp lady since her timewe seem to have gotten bit more confused about what we mean when we say scripting it confuses even meand ' supposed to be one of the experts there are many other widely used computer science terms to pick up writing program (or script or codeis often expressed as implementing the program executing program means running the program an algorithm is recipe for how to construct program bug is an error in programand the art of tracking down and removing bugs is called debugging simulating or simulation refers to using program to mimic processes in the real worldoften through solving differential equations that govern the physics of the processes python program with variables our first example regards programming mathematical model that predicts the position of ball thrown up in the air from newton' nd lawand by assuming negligible air resistanceone can derive mathematical model that predicts the vertical position of the ball at time from the model one gets the formula : gt where is the initial upwards velocity and is the acceleration of gravityfor which : ms is reasonable value (even if it depends on things like location on the earthwith this formula at handand when is knownyou may plug in value for time and get out the corresponding height
3,751
the first few steps the program let us next look at python program for evaluating this simple formula assume the program is contained as text in file named ball py the text looks as follows (file ball py)program for computing the height of ball in vertical motion initial velocity acceleration of gravity time * * * ** vertical position print computer programs and parts of programs are typeset with blue background in this book slightly darker top and bottom baras aboveindicates that the code is complete program that can be run as it stands without the barsthe code is just snippet and will (normallyneed additional lines to run properly dissection of the program computer program is plain textas here in the file ball pywhich contains instructions to the computer humans can read the code and understand what the program is capable of doingbut the program itself does not trigger any actions on computer before another programthe python interpreterreads the program text and translates this text into specific actions you must learn to play the role of computer although python is responsible for reading and understanding your programit is of fundamental importance that you fully understand the program yourself you have to know the implication of every instruction in the program and be able to figure out the consequences of the instructions in other wordsyou must be able to play the role of computer the reason for this strong demand of knowledge is that errors unavoidablyand quite oftenwill be committed in the program textand to track down these errorsyou have to simulate what the computer does with the program nextwe shall explain all the text in ball py in full detail when you run your program in pythonit will interpret the text in your file line by linefrom the topreading each line from left to right the first line it reads is program for computing the height of ball in vertical motion this line is what we call comment that isthe line is not meant for python to read and executebut rather for human that reads the code and tries to understand what is going on thereforeone rule in python says that whenever python encounters
3,752
the sign it takes the rest of the line as comment python then simply skips reading the rest of the line and jumps to the next line in the codeyou see several such comments and probably realize that they make it easier for you to understand (or guesswhat is meant with the code in simple casescomments are probably not much neededbut will soon be justified as the level of complexity steps up the next line read by python is initial velocity in pythona statement like is known as an assignment statement (very different from mathematical equation!the result on the right-hand sidehere the integer becomes an object and the variable name on the left-hand side is named reference for that object whenever we write python will replace it by an integer with value doing creates new namev for the same integer object with value and not copy of an integer object with value the next two lines acceleration of gravity time are of the same kindso having read them toopython knows of three variables ( gtand their values these variables are then used by python when it reads the next linethe actual "formula" * * * ** vertical position againaccording to its rulespython interprets as multiplicationas minus and *as exponent (let us also add here thatnot surprisinglyand would have been understood as addition and divisionif such signs had been present in the expressionhaving read the linepython performs the mathematics on the righthand sideand then assigns the result (in this case the number to the variable name finallypython reads print this makes python print the value of out in that window on the screen where you started the program when ball py is runthe number appears on the screen in the code aboveyou see several blank lines too these are simply skipped by python and you may use as many as you want to make nice and readable layout of the code why not just use pocket calculatorcertainlyfinding the answer as done by the program above could easily have been done with pocket calculator no objections to that and no programming would have been needed howeverwhat if you would like to have the position of the ball
3,753
the first few steps for every milli-second of the flightall that punching on the calculator would have taken you something like four hoursif you know how to programhoweveryou could modify the code above slightlyusing minute or two of writingand easily get all the positions computed in one go within second much stronger argumenthoweveris that mathematical models from real life are often complicated and comprehensive the pocket calculator cannot cope with such problemseven not the programmable onesbecause their computational power and their programming tools are far too weak compared to what real computer can offer why you must use text editor to write programs when python interprets some code in fileit is concerned with every character in the fileexactly as it was typed in this makes it troublesome to write the code into file with word processors likee microsoft wordsince such program will insert extra charactersinvisible to uswith information on how to format the text ( the font size and typesuch extra information is necessary for the text to be nicely formatted for the human eye pythonhoweverwill be much annoyed by the extra characters in the file inserted by word processor thereforeit is fundamental that you write your program in text editor where what you type on the keyboard is exactly the characters that appear in the file and that python will later read there are many text editors around some are stand-alone programs like emacsvimgeditnotepad++and textwrangler others are integrated in graphical development environments for pythonsuch as spyder this book will primarily refer to spyder and its text editor installation of python you will need access to python and several add-on packages for doing mathematical computations and display graphics an obvious choice is to install python environment for scientific computing on your machine alternativelyyou can use cloud services for running pythonor you can remote login on computer system at school or university available and recommended techniques for getting access to python and the needed packages are documented in appendix the quickest way to get started with python installation for this book on your windowsmacor linux computeris to install anaconda write and run your first program reading only does not teach you computer programmingyou have to program yourself and practice heavily before you master mathematical problem solving via programming thereforeit is crucial at this stage that you write and run python program we just went through the program ball py aboveso let us next write and run that code
3,754
python program with library function but first warningthere are many things that must come together in the right way for ball py to run correctly on your computer there might be problems with your python installationwith your writing of the program (it is very easy to introduce errors!)or with the location of the filejust to mention some of the most common difficulties for beginners fortunatelysuch problems are solvableand if you do not understand how to fix the problemask somebody typicallyonce you are beyond these common start-up problemsyou can move on to learn programming and how programs can do lot of otherwise complicated mathematics for you we describe the first steps using the spyder graphical user interface (gui)but you can equally well use standard text editor for writing the program and terminal window (terminal on macpower shell on windowsfor running the program start up spyder and type in each line of the program ball py shown earlier then run the program more detailed descriptions of operating spyder are found in appendix if you have had the necessary luck to get everything rightyou should now get the number out in the rightmost lower window in the spyder gui if socongratulationsyou have just executed your first self-written computer program in pythonand you are ready to go on studying this bookyou may like to save the program before moving on (filesave as python program with library function imagine you stand on distancesay awaywatching someone throwing ball upwards straight line from you to the ball will then make an angle with the horizontal that increases and decreases as the ball goes up and down let us consider the ball at particular moment in timeat which it has height of what is the angle of the line thenagainthis could easily be done with calculatorbut we continue to address gentle mathematical problems when learning to program before thinking of writing programone should always formulate the algorithmi the recipe for what kind of calculations that must be performed hereif the ball is away and up in the airit makes an angle with the groundwhere tan = the angle is then tan =xlet us make python program for doing these calculations we introduce names and for the position data and yand the descriptive name angle for the angle the program is stored in file ball_angle_first_try pyx horizontal position vertical position angle atan( /xprint (angle/pi)* before we turn our attention to the running of this programlet us take look at one new thing in the code the line angle atan( / )illustrates how the function atancorresponding to tan in mathematicsis called with the ratio
3,755
the first few steps / as input parameter or argument the atan function takes one argumentand the computed value is returned from atan this means that where we see atan( / ) computation is performed (tan = /and the result "replacesthe text atan( /xthis is actually no more magic than if we had written just /xthen the computation of / would take placeand the result of that division would replace the text / thereafterthe result is assigned to the name angle on the left-hand side of note that the trigonometric functionssuch as atanwork with angles in radians the return value of atan must hence be converted to degreesand that is why we perform the computation (angle/pi)* two things happen in the print statementfirstthe computation of (angle/pi)* is performedresulting in real numberand secondprint prints that real number againwe may think that the arithmetic expression is replaced by its results and then print starts working with that result if we next execute ball_angle_first_try pywe get an error message on the screen saying nameerrorname 'atanis not defined warningfailure executing filewe have definitely run into troublebut whywe are told that name 'atanis not defined so apparently python does not recognize this part of the code as anything familiar on pocket calculator the inverse tangent function is straightforward to use in similar way as we have written in the code in pythonhoweverthis function has not yet been imported into the program lot of functionality is available to us in programbut much more functionality exists in python librariesand to activate this functionalitywe must explicitly import it in pythonthe atan function is grouped together with many other mathematical functions in the library called math such library is referred to as module in correct python language to get access to atan in our program we have to write from math import atan inserting this statement at the top of the program and rerunning itleads to new problempi is not defined the variable pirepresenting is also available in the math modulebut it has to be imported toofrom math import atanpi it is tedious if you need quite some math functions and variables in your programe also sincoslogexpand so on quick way of importing everything in math at onceis from math import
3,756
we will often use this import statement and then get access to all common mathematical functions this latter statement is inserted in program named ball_angle pyfrom math import horizontal position vertical position angle atan( /xprint (angle/pi)* this program runs perfectly and produces as outputas it should at firstit may seem cumbersome to have code in librariessince you have to know which library to import to get the desired functionality having everything available anytime would be convenientbut this also means that you fill up the memory of your program with lot of information that you rather would use for computations on big data python has so many libraries with so much functionality that one simply needs to import what is needed in specific program python program with vectorization and plotting we return to the problem where ball is thrown up in the air and we have formula for the vertical position of the ball say we are interested in at every millisecond for the first second of the flight this requires repeating the calculation of : gt one thousand times we will also draw graph of versus for oe drawing such graphs on computer essentially means drawing straight lines between points on the curveso we need many points to make the visual impression of smooth curve with one thousand pointsas we aim to compute herethe curve looks indeed very smooth in pythonthe calculations and the visualization of the curve may be done with the program ball_plot pyreading from numpy import linspace import matplotlib pyplot as plt linspace( * * * ** plt plot(typlt xlabel(' ( )'plt ylabel(' ( )'plt show(
3,757
the first few steps this program produces plot of the vertical position with timeas seen in figure as you noticethe code lines from the ball py program in have not changed muchbut the height is now computed and plotted for thousand points in timelet us take look at the differences between the new program and our previous program from the topthe first difference we notice are the lines from numpy import from matplotlib pyplot import you see the word import hereso you understand that numpy must be libraryor module in python terminology this library contains lot of very useful functionality for mathematical computingwhile the matplotlib pyplot module contains functionality for plotting curves the above import statement constitutes quick way of populating your program with all necessary functionality for mathematical computing and plotting howeverwe actually make use of only few functions in the present programlinspaceplotxlabeland ylabel many computer scientists will therefore argue that we should explicitly import what we need and not everything (the star *)from numpy import linspace from matplotlib pyplot import plotxlabelylabel others will claim that we should do slightly different import and prefix library functions by the library nameimport numpy as np import matplotlib pyplot as plt np linspace( plt plot(typlt xlabel(' ( )'plt ylabel(' ( )'we will use all three techniquesand since all of them are in so widespread useyou should be familiar with them too howeverfor the most part in this book we shall do from numpy import from matplotlib pyplot import for convenience and for making python programs that look very similar to their matlab counterparts the function linspace takes parametersand is generally called as linspace(startstopnthis is our first example of python function that takes multiple arguments the linspace function generates equally spaced coordinatesstarting with start
3,758
fig plot generated by the script ball_plot py showing the vertical position of the ball at thousand points in time and ending with stop the expression linspace( creates coordinates between and (including both and the mathematically inclined reader will notice that coordinates correspond to equal-sized intervals in oe and that the coordinates are then given by ti = ( the value returned from linspace (being stored in tis an arrayi collection of numbers when we start computing with this collection of numbers in the arithmetic expression * * * ** the expression is calculated for every number in ( every ti for )yielding similar collection of numbers in the result that isy is also an array this technique of computing all numbers "in one chunkis referred to as vectorization when it can be usedit is very handysince both the amount of code and computation time is reduced compared to writing corresponding for or while loop (for doing the same thing the plotting commands are simple plot(tymeans plotting all the coordinates versus all the coordinates xlabel(' ( )'places the text (son the axis ylabel(' ( )'places the text (mon the axis at this stageyou are strongly encouraged to do exercise it builds on the example abovebut is much simpler both with respect to the mathematics and the amount of numbers involved
3,759
the first few steps more basic concepts so far we have seen few basic examples on how to apply python programming to solve mathematical problems before we can go on with other and more realistic exampleswe need to briefly treat some topics that will be frequently required in later these topics include computer science concepts like variablesobjectserror messagesand warningsmore numerical concepts like rounding errorsarithmetic operator precedenceand integer divisionin addition to more python functionality when working with arraysplottingand printing using python interactively python can also be used interactively that iswe do not first write program in file and execute itbut we give statements and expressions to what is known as python shell we recommend to use ipython as shell (because it is superior to alternative python shellswith spyderipython is available at startupappearing as the lower right window following the ipython prompt in [ ] prompt means "ready sign" the program allows you to enter commandand different programs often have different looking prompts)you may do calculationsin [ ] + out [ ] in [ ] * out [ ] in [ ] / out [ ] in [ ] ** out [ ] the response from ipython is preceded by out [ ]:where equals when the response is to input "numberp note thatas in programyou may have to use import before using pi or functions like sincosetc that isat the promptdo the command from math import before you use pi or sinetc importing other modules than math may be relevantdepending on what your aim is with the computations you may also define variables and use formulas interactively as in [ ] in [ ] in [ ] in [ ] * * * ** in [ ]print print(
3,760
sometimes you would like to repeat command you have given earlieror perhaps give command that is almost the same as an earlier one then you can use the up-arrow key pressing this one time gives you the previous commandpressing two times gives you the command before thatand so on with the down-arrow key you can go forward again when you have the relevant command at the promptyou may edit it before pressing enter (which lets python read it and take actionarithmeticsparentheses and rounding errors when the arithmetic operators +-*and *appear in an expressionpython gives them certain precedence python interprets the expression from left to righttaking one term (part of expression between two successive or -at time within each term*is done before and consider the expression * ** * there are three terms here and interpreting thispython starts from the left in the first term * ** it first does ** which equals this is then multiplied by to give again the second term is * so the first two terms add up to the last term gives so the final result is which becomes the value of note that parentheses are often very important to group parts of expressions together in the intended way let us say and that you want to divide by we know the answer is but the way we present the task to python is criticalas shown by the following example in [ ] in [ ] / + out [ ] in [ ] /( + out [ ] in the first trywe see that is divided by ( )giving which is then added to python did not understand that our complete denominator was + in our second trywe used parentheses to "groupthe denominatorand we got what we wanted that isalmost what we wantedsince most numbers can be represented only approximately on the computerthis gives rise to what is called rounding errors we should have got as our answerbut the inexact number representation gave small error usuallysuch errors are so small compared to the other numbers of the calculationthat we do not need to bother with them stillkeep it in mindsince you will encounter this issue from time to time more details regarding number representations on computer is given in section variables and objects variables in python will be of certain type if you have an integersay you have written in some python programthen becomes an integer variablei variable of type int similarlywith the statement becomes float
3,761
the first few steps variable (the word float is just computer language for real numberin any casepython thinks of as an objectof type int or float another common type of variable is stri stringneeded when you want to store text when python interprets "this is string"it stores the text (in between the quotesin the variable this variable is then an object of type str you may convert between variable types if it makes sense ife is an int objectwriting float(xwill make floating point representation of similarlyyou may write int(xto produce an int if is originally of type float type conversion may also occur automaticallyas shown just below names of variables should be chosen so that they are descriptive when computing mathematical quantity that has some standard symbole ,this should be reflected in the name by letting the word alpha be part of the name for the corresponding variable in the program if youe have variable for counting the number of sheepthen one appropriate name could be no_of_sheep such naming makes it much easier for human to understand the written code variable names may also contain any digit from to or underscoresbut can not start with digit letters may be lower or upper casewhich to python is different note that certain names in python are reservedmeaning that you can not use these as names for variables some examples are forwhileifelseglobalreturn and elif if you accidentally use reserved word as variable name you get an error message we have seen thate will assign the value to the variable but how do we write it if we want to increase by we may write an assignment like or (giving faster computationx + now python interprets this astake whatever value that is in xadd and let the result become the new value of in other wordsthe old value of is used on the right hand side of =no matter how messy the expression might beand the result becomes the new value of in similar wayx - reduces the value of by * multiplies by and / divides by updating the value of accordingly what if an object of type intand we add floatthen automatic type conversion takes placeand the new will have the value an object of type float as seen herein [ ] in [ ] in [ ] out [ ] note that python programmersand python (in printouts)often writee which by definition is the integer represented as float integer division another issue that is important to be aware of is integer division let us look at small exampleassuming we want to divide one by four
3,762
in [ ] / out [ ] in [ ]out [ ] we see two alternative ways of writing itbut only the last way of writing it gave the correct ( expectedresultwhywith python version the first alternative gives what is called integer divisioni all decimals in the answer are disregardedso the result is rounded down to the nearest integer to avoid itwe may introduce an explicit decimal point in either the numeratorthe denominatoror in both if you are new to programmingthis is certainly strange behavior howeveryou will find the same feature in many programming languagesnot only pythonbut actually all languages with significant inheritance from if your numerator or denominator is variablesay you have /xyou may write /float(xto be on safe grounds python version implements mathematical real number division by and requires the operator /for integer division (/is also available in python version although python version eliminates the problems with unintended integer divisionit is important to know about integer division when doing computing in most other languages formatting text and numbers results from scientific computations are often to be reported as mixture of text and numbers usuallywe want to control how numbers are formatted for examplewe may want to write / as or - ( :  the print command is the key tool to write out text and numbers with full control of the formatting the first argument to print is string with particular syntax to specify the formattingthe so-called printf syntax (the peculiar name stems from the printf function in the programming language where the syntax was first introduced suppose we have real number an integer and text 'some messagethat we want to write out in the following two alternative waysreal= integer= string=some message real= + integer string=some message the real number is first written in decimal notation with three decimalsas but afterwards in scientific notation as + the integer is first written as compactly as possiblewhile on the second line is formatted in text field of width equal to five characters the following programformatted_print pyapplies the printf syntax to control the formatting displayed above
3,763
the first few steps real integer string 'some messageprint 'real= finteger=%dstring=% (realintegerstringprint 'real=% einteger=% dstring=% (realintegerstringthe output of print is stringspecified in terms of text and set of variables to be inserted in the text variables are inserted in the text at places indicated by after comes specification of the formattinge % (real number)% (integer)or % (stringthe format % means real number in decimal notationwith decimalswritten in field of width equal to characters the variant means that the number is written as compactly as possiblein decimal notationwith three decimals switching with or results in the scientific notationhere + or + writing % means that an integer is to be written in field of width equal to characters real numbers can also be specified with %gwhich is used to automatically choose between decimal or scientific notationfrom what gives the most compact output (typicallyscientific notation is appropriate for very small and very large numbers and decimal notation for the intermediate rangea typical example of when printf formatting is requiredarises when nicely aligned columns of numbers are to be printed suppose we want to print column of values together with associated function values td sin tin second column the simplest approach would be from math import sin dt unformatted print *dtg *sin(tprint tg *dtg *sin(tprint tg *dtg *sin(tprint tg with output (repeating the same set of statements multiple timesas done aboveis not good programming practice one should use for loopas explained later in section observe that the numbers in the columns are not nicely aligned using the printf syntax '% % (tgfor and gwe can control the width of each column and also the number of decimalssuch that the numbers in column are
3,764
aligned under each other and written with the same precision the output then becomes formatting via printf syntax we shall frequently use the printf syntax throughout the book so there will be plenty of further examples the modern alternative to printf syntax modern python favors the new format string syntax over printfprint 'at ={ :gsy={ fmformat( =ty=ywhich corresponds to the printf syntax print 'at =% sy= (tythe slots where variables are inserted are now recognized by curly bracesand in format we list the variable names inside curly braces and their equivalent variables in the program since the printf syntax is so widely used in many programming languageswe stick to that in the present bookbut python programmers will frequently also meet the newer format string syntaxso it is important to be aware its existence arrays in the program ball_plot py from we saw how height computations were executed and stored in the variable yand then displayed in plot showing versus ti height versus time the collection of numbers in (or trespectivelywas stored in what is called an arraya construction also found in most other programming languages such arrays are created and treated according to certain rulesand as programmeryou may direct python to compute and handle arrays as wholeor as individual array elements let us briefly look at smaller such collection of numbers assume that the heights of four family members have been collected these heights may be generated and stored in an arraye named hby writing zeros( [ [ [ [ where the array elements appear as [ ] [ ]etc generallywhen we read or talk about the array elements of some array awe refer to them by reading or saying
3,765
the first few steps " of zero( [ ])" of one( [ ])and so on the very first line in the example abovei zeros( instructs python to reserveor allocatespace in memory for an array with four elements and initial values set to the next four lines overwrite the zeros with the desired numbers (measured heights)one number for each element elements areby ruleindexed (numbers within bracketsfrom to the last elementin this case we say that python has zero based indexing this differs from one based indexing ( found in matlabwhere the array index starts with as illustrated in the codeyou may refer to the array as whole by the name hbut also to each individual element by use of the index the array elements may enter in computations as individual variablese writing [ [ [ [ will compute the sum of all the elements in hwhile the result is assigned to the variable note that this way of creating an array is bit different from the one with linspacewhere the filling in of numbers occurred automatically "behind the sceneby the use of colonyou may pick out slice of an array for exampleto create new array from the two elements [ and [ ]we could write slice_h [ : note that the index specification : means indices and the last index is not included for the generated slice_h arrayindices are as usuali and in this case the very last entry in an array may be addressed ase [- copying arrays requires some care since simply writing new_h willwhen you afterwards change elements of new_halso change the corresponding elements in hthat ish[ is also changed when writing new_h new_h[ print [ in this case we do not get out on the screenbut to really get copy that is decoupled from the original arrayyou may write new_h copy(hhowevercopying slice works straightforwardly (as shown above) an explicit use of copy is not required plotting sometimes you would like to have two or more curves or graphs in the same plot assume we have as aboveand also an array with the heights mand from family next door this may be done with the program plot_heights py given as
3,766
fig generated plot for the heights of family members from two families from numpy import zeros import matplotlib pyplot as plt zeros( [ [ [ [ zeros( [ [ [ [ family_member_no zeros( family_member_no[ family_member_no[ family_member_no[ family_member_no[ plt plot(family_member_nohfamily_member_nohplt xlabel('family member number'plt ylabel('height ( )'plt show(running the program gives the plot shown in figure alternativelythe two curves could have been plotted in the same plot by use of two plot commandswhich gives more freedom as to how the curves appear to do thisyou could plot the first curve by plt plot(family_member_nohplt hold('on'
3,767
the first few steps then you could (in principledo lot of other things in your codebefore you plot the second curve by plt plot(family_member_nohplt hold('off'notice the use of hold here hold('on'tells python to plot also the following curve(sin the same window python does so until it reads hold('off'if you do not use the hold('on'or hold('off'commandthe second plot command will overwrite the first onei you get only the second curve in case you would like the two curves plotted in two separate plotsyou can do this by plotting the first curve straightforwardly with plt plot(family_member_nohthen do other things in your codebefore you do plt figure(plt plot(family_member_nohnote how the graphs are made continuous by pythondrawing straight lines between the four data points of each family this is the standard way of doing it and was also done when plotting our height computations with ball_plot py in howeversince there were so many data points thenthe curve looked nice and smooth if preferredone may also plot only the data points for examplewriting plt plot( '*'will mark only the data points with the star symbol other symbols like circles etc may be used as well there are many possibilities in python for adding information to plot or for changing its appearance for exampleyou may add legend by the instruction plt legend('this is some legend'or you may add title by plt title('this is some title'the command plt axis([xminxmaxyminymax]will define the plotting range for the axis to stretch from xmin to xmax andsimilarlythe plotting range for the axis from ymin to ymax saving the figure to file is achieved by the command
3,768
plt savefig('some_plot png'plt savefig('some_plot pdf'plt savefig('some_plot jpg'plt savefig('some_plot eps'png format pdf format jpg format encanspulated postscript format for the reader who is into linear algebrait may be useful to know that standard matrix/vector operations are straightforward with arrayse matrix-vector multiplication what is needed thoughis to create the right variable types (after having imported an appropriate modulefor exampleassume you would like to calculate the vector (note that boldface is used for vectors and matricesas axwhere is matrix and is vector we may do this as illustrated by the program matrix_vector_product py reading from numpy import zerosmattranspose zeros( mat(xx transpose(xx[ [ pick some values zeros(( , ) mat(aa[ , [ , [ , [ , the following gives since ithe identity matrix * print herex is first created as an arrayjust as we did above then the variable type of is changed to mati matrixby the line mat(xthis is followed by transpose of from dimension (the default dimensionto with the statement transpose( )before some test values are plugged in the matrix is first created as two dimensional array with zeros(( , )before conversion and filling in values take place finallythe multiplication is performed as * note the number of parentheses when creating the two dimensional array running the program gives the following output on the screen[[ [ ]error messages and warnings all programmers experience error messagesand usually to large extent during the early learning process sometimes error messages are understandablesometimes they are not anywayit is important to get used to them one idea is to start with program that initially is workingand then deliberately introduce errors in itone by one (but remember to take copy of the original working code!for each error
3,769
the first few steps you try to run the program to see what python' response is then you know what the problem is and understand what the error message is about this will greatly help you when you get similar error message or warning later very oftenyou will experience that there are errors in the program you have written this is normalbut frustrating in the beginning you then have to find the problemtry to fix itand then run the program again typicallyyou fix one error just to experience that another error is waiting around the corner howeverafter some time you start to avoid the most common beginner' errorsand things run more smoothly the process of finding and fixing errorscalled debuggingis very important to learn there are different ways of doing it too special program (debuggermay be used to help you check (and dodifferent things in the program you need to fix simpler procedurethat often brings you long wayis to print information to the screen from different places in the program first of allthis is something you should do (several timesduring program development anywayso that things get checked as you go along howeverif the final program still ends up with error messagesyou may save copy of itand do some testing on the copy useful testing may then be to removee the latter half of the program (by inserting comment signs #)and insert print commands at clever places to see what is the case when the first half looks okinsert parts of what was removed and repeat the process with the new code using simple numbers and doing this in parallel with hand calculations on piece of paper (for comparisonis often very good idea python also offers means to detect and handle errors by the program itselfthe programmer must then foresee (when writing the codethat there is potential for error at some particular point iffor examplesome user of the program is asked (by the running programto provide numberand intends to give the number but instead writes the word fivethe program could run into trouble try-exception construction may be used by the programmer to check for such errors and act appropriately (see for an example)avoiding program crash this procedure of trying an action and then recovering from troubleif necessaryis referred to as exception handling and is the modern way of dealing with errors in program when program finally runs without error messagesit might be tempting to think that ah am finishedbut nothen comes program testingyou need to verify that the program does the computations as planned this is almost an art and may take more time than to develop the programbut the program is useless unless you have much evidence showing that the computations are correct alsohaving set of (automatictests saves huge amounts of time when you further develop the program verification versus validation verification is importantbut validation is equally important it is great if your program can do the calculations according to the planbut is it the right planput otherwiseyou need to check that the computations run correctly according to the formula you have chosen/derived this is verificationdoing the things right thereafteryou must also check whether the formula you have chosen/derived is the right formula for the case you are investigating this is validationdoing the right things in the present bookit is beyond scope to question how well the mathematical models describe given phenomenon in nature or engineering
3,770
as the answer usually involves extensive knowledge of the application area we will therefore limit our testing to the verification part input data computer programs need set of input data and the purpose is to use these data to compute output datai results in the previous program we have specified input data in terms of variables howeverone often wants to get the input through some dialog with the user here is one example where the program asks questionand the user provides an answer by typing on the keyboardage input('what is your age'print "okso you're half way to %dwow!(age* soafter having interpreted and run the first linepython has established the variable age and assigned your input to it the second line combines the calculation of twice the age with message printed on the screen try these two lines in little test program to see for yourself how it works the input function is useful for numberslists ()and tuples (for pure textthe user must either enclose the input in quotesor the program must use the raw_input function insteadname raw_input('what is your name'there are other ways of providing input to program as welle via graphical interface (as many readers will be used toor at the command line ( as parameters succeedingon the same linethe command that starts the programreading data from file is yet another way logicallywhat the program produces when rune plot or printout to the screen or fileis referred to as program output symbolic computations even though the main focus in this book is programming of numerical methodsthere are occasions where symbolic (also called exact or analyticaloperations are useful doing symbolic computations meansas the name suggeststhat we do computations with the symbols themselves rather than with the numerical values they could represent let us illustrate the difference between symbolic and numerical computations with little example numerical computation could be * print which will make the number appear on the screen symbolic counterpart of this code could be
3,771
the first few steps from sympy import xy symbols(' ' * print which causes the symbolic result * to appear on the screen note that no numerical value was assigned to any of the variables in the symbolic computation only the symbols were usedas when you do symbolic mathematics by hand on piece of paper symbolic computations in python make use of the sympy package each symbol is represented by standard variablebut the name of the symbol must be declared with symbol(namefor single symbolor symbols(name name for multiple symbols the following script example_symbolic py is quick demonstration of some of the basic symbolic operations that are supported in python from sympy import symbol(' ' symbol(' 'print * * algebraic computation print diff( ** xdifferentiates ** wrt print integrate(cos( )xintegrates cos(xwrt print simplify(( ** ** )/ ** simplifies expression print limit(sin( )/xx finds limit of sin( )/ as -> print solve( * xsolves * other symbolic calculations like taylor series expansionlinear algebra (with matrix and vector operations)and (somedifferential equation solving are also possible symbolic computations are also readily accessible through the (partlyfree online tool wolframalpha which applies the very advanced mathematica package as symbolic engine the disadvantage with wolframalpha compared to the sympy package is that the results cannot automatically be imported into your code and used for further analysis on the other handwolframalpha has the advantage that it displays many additional mathematical results related to the given problem for exampleif we type in wolframalphait not only simplifies the expression to ybut it also makes plots of the function fr xr yd ysolves the equation and calculates the integral /dxdy the commercial pro version can also show step-by-step of the analytical computations in the problem you are strongly encouraged to try out these commands in wolframalphadiff( ^ xor diff( ** xintegrate(cos( )xsimplify(( ** ** )/ **
3,772
limit(sin( )/xx solve( * xwolframalpha is very flexible with respect to syntax another impressive tool for symbolic computations is sage which is very comprehensive package with the aim of "creating viable free open source alternative to magmamaplemathematica and matlabsage is implemented in python projects with extensive symbolic computations will certainly benefit from exploring sage concluding remarks programming demands you to be accuratein this you have seen some examples of how simple things may be done in python hopefullyyou have tried to do the examples on your own if you havemost certainly you have discovered that what you write in the code has to be very accurate for examplewith our previous example of four heights collected in an array hwriting ( instead of [ gives an erroreven if you and know perfectly well what you meanremember that it is not human that runs your codeit is machine thereforeeven if the meaning of your code looks fine to human eyeit still has to comply in detail to the rules of the programming language if notyou get warnings and error messages this also goes for lower and upper case letters if you do from math import and give the command piyou get : howeverif you write piyou get an error message pay attention to such details also when they are given in later remember to insert comments to explain your code when you write computer programyou have two very different kinds of readers one is pythonwhich will interpret and run your program according to the rules the other is some humanfor exampleyourself or peer it is very important to organize and comment the code so that you can go back to your own code aftere year and still understand what clever constructions you put in there this is relevant when you need to change or extend your code (which usually happens often in realityorganized coding and good commenting is even more critical if other people are supposed to understand code that you have written fast code versus readable and correct code numerical computing has strong tradition in paying much attention to creating fast code real industrial applications of numerical computing often involves simulations that run for hoursdaysand even weeks fast code is tremendously important in those cases the problem with strong focus on fast codeunfortunatelyis sometimes that clear and easily understandable constructions are replaced by clever and less readablebut faster code howeverfor beginners it is most important to learn to write readable and correct code we will make some
3,773
the first few steps comments on constructions that are fast or slowbut the main focus of this book is to teach how to write correct programsnot the fastest possible programs deleting data no longer in use python has automatic garbage collectionmeaning that there is no need to delete variables (or objectsthat are no longer in use python takes care of this by itself this is opposed toe matlabwhere explicit deleting sometimes may be required tiphow to deal with long lines if statement in program gets too longit may be continued on the next line by inserting back-slash at the end of the line before proceeding on the next line howeverno blanks must occur after the back-slashthe present introductory book just provides tiny bit of all the functionality that python has to offer an important source of information is the official python documentation website (the python library referencea language referenceand more several excellent books are also available (many with scientific computing focus one exception is langtangen' comprehensive book primer on scientific programming with pythonspringer exercises exercise error messages save copy of the program ball py and confirm that the copy runs as the original you are now supposed to introduce errors in the codeone by one for each error introducedsave and run the programand comment how well python' response corresponds to the actual error when you are finished with one errorre-set the program to correct behavior (and check that it works!before moving on to the next error ainsert the word hello on the empty line above the assignment to bremove the sign in front of the comment initial velocity cremove the sign in the assignment to dchange the reserved word print into pint echange the calculation of to * fchange the line print to print greplace the statement * * * ** by * ( / )* * ** filenametesting_ball py
3,774
exercise volume of cube write program that computes the volume of cube with sides of length cm and prints the result to the screen both and should be defined as separate variables in the program run the program and confirm that the correct result is printed hint see ball py in the text filenamecube_volume py exercise area and circumference of circle write program that computes both the circumference and the area of circle with radius cm let the results be printed to the screen on single line with an appropriate text the variables and should all be defined as separate variables in the program run the program and confirm that the correct results are printed filenamecircumference_and_area py exercise volumes of three cubes we are interested in the volume of cube with length lv computed for three different values of ause the linspace function to compute three values of lequally spaced on the interval oe bcarry out by hand the computation if is an array with three elements that iscompute for each value of cin programwrite out the result of ** when is an array with three elements as computed by linspace in acompare the resulting volumes with your hand calculations dmake plot of versus filenamevolume cubes py exercise average of integers write program that stores the sum in one variable and then creates another variable with the average of these five numbers print the average to the screen and check that the result is correct filenameaverage_int py exercise interactive computing of volume and area acompute the volume in exercise by using python interactivelyi do the computations at the command prompt (in python shell as we also saycompare with what you got previously from the written program bdo the same also for exercise
3,775
the first few steps exercise peculiar results from division consider the following interactive python sessionin [ ] = = in [ ] / out[ ] what is the problem and how can you fix itexercise update variable at command prompt invoke python interactively and perform the following steps initialize variable to add to print out the result print out the result of * and ( + )* (observe how parentheses make difference what variable type is xexercise formatted print to screen write program that defines two variables as pi and then let the program compute the product of these two variables and print the result to the screen as multiplying and gives filenameformatted_print py exercise python documentation and random numbers write program that prints four random numbers to the screen the numbers should be drawn from uniform distribution over the interval oe ( inclusive exclusivefind the information needed for the tasksee for example org hint python has module random that contains function by the name uniform filenamedrawing_random_numbers 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,776
basic constructions if testscolon and indentation very often in lifeand in computer programsthe next action depends on the outcome of question starting with "ifthis gives the possibility to branch into different types of action depending on some criterion let us as usual focus on specific examplewhich is the core of so-called random walk algorithms used in wide range of branches in science and engineeringincluding materials manufacturing and brain research the action is to move randomly to the north ( )east ( )south ( )or west (wwith the same probability how can we implement such an action in life and in computer programwe need to randomly draw one out of four numbers to select the direction in which to move deck of cards can be used in practice for this purpose let the four suits correspond to the four directionsclubs to ndiamonds to ehearts to sand spades to wfor instance we draw cardperform the corresponding moveand repeat the process large number of times the resulting path is typical realization of the path of diffusing molecule in computer programwe need to draw random numberand depending on the numberupdate the coordinates of the point to be moved there are many ways to draw random numbers and translate them into ( four random directionsbut the technical details usually depend on the programming language our technique here is universalwe draw random number in the interval oe and let oe : correspond to noe : : to eoe : : to sand oe : to let and (cthe author( lingeh langtangenprogramming for computations pythontexts in computational science and engineering doi --
3,777
basic constructions hold the coordinates of point and let be the length of the move pseudo code ( not "realcodejust "sketch of the logic"then goes like random number in [ , if < move northy else if < move eastx else if < move southy else if < move westx note the need for first asking about the value of and then performing an action if the answer to the "ifquestion is positive (true)we are done and can skip the next else if questions if the answer is negative (false)we proceed with the next question the last test if : could also read just elsesince we here cover all the remaining possible values the exact code in python reads import random random random(if < move north elif < move east elif < move south elsemove west random number in [ , we use else in the last test to cover the different types of syntax that is allowed python recognizes the reserved words ifelif (short for else if)and else and expects the code to be compatible with the rules of if teststhe test reads if condition:elif condition:or else:where condition is boolean expression that evaluates to true or false note the closing colon (easy to forget!if condition is truethe following indented block of statements is executed and the remaining elif or else branches are skipped if condition is falsethe program flow jumps to the next elif or else branch the blocks after ifelifor else may contain new if testsif desired regarding colon and indentyou will see below that these are required in several other programming constructions as well working with if tests requires mastering boolean expressions here are some basic boolean expressions involving the logical operators ==!=and
3,778
>given the assignment to tempyou should go through each boolean expression below and determine if it is true or false temp temp = temp ! temp temp temp < temp > assign value to variable temp equal to temp not equal to temp less than temp greater than temp less than or equal to temp greater than or equal to functions functions are widely used in programming and is concept that needs to be mastered in the simplest casea function in program is much like mathematical functionsome input number is transformed to some output number one example is the tanh xfunctioncalled atan in computer codeit takes one real number as input and returns another number functions in python are more general and can take series of variables as input and return one or more variablesor simply nothing the purpose of functions is two-fold to group statements into separate units of code lines that naturally belong together strategy which may dramatically ease the problem solving process)and/or to parameterize set of statements such that they can be written only once and easily be re-executed with variations examples will be given to illustrate how functions can be written in various contexts if we modify the program ball py from sect slightlyand include functionwe could let this be new program ball_function py as def ( ) return * * * ** time print (timetime print (timeinitial velocity acceleration of gravity just pick one point in time pick another point in time when python reads and interprets this program from the topit takes the code from the line with defto the line with returnto be the definition of function with the name (note colon and indentationthe return statement of the function yi return * * * **
3,779
basic constructions will be understood by python as first compute the expressionthen send the result back ( returnto where the function was called from both def and return are reserved words the function depends on ti one variable (or we say that it takes one argument or input parameter)the value of which must be provided when the function is called what actually happens when python meets this codethe def line just tells python that here is function with name and it has one argument python does not look into the function at this stage (except that it checks the code for syntax errorswhen python later on meets the statement print (time)it recognizes function call (timeand recalls that there is function defined with one argument the value of time is then transferred to the (tfunction such that time becomes the first action in the function then python executes one line at time in the function in the final linethe arithmetic expression * * * ** is computedresulting in numberand this number (or more preciselythe python object representing the numberreplaces the call (timein the calling code such that the word print now precedes number rather than function call python proceeds with the next line and sets time to new value the next print statement triggers new call to ( )this time is set to the computations are done line by line in the functionand the returned result replaces (timeinstead of writing print (time)we could alternatively have stored the returned result from the function in variableh (timeprint note that when function contains if-elif-else constructionsreturn may be done from within any of the branches this may be illustrated by the following function containing three return statementsdef check_sign( )if return ' is positiveelif return ' is negativeelsereturn ' is zeroremember that only one of the branches is executed for single call on check_ signso depending on the number xthe return may take place from any of the three return alternatives to return at the end or not programmers disagree whether it is good idea to use return inside function where you wantor if there should only be one single return statement at the end of the function the authors of this book emphasize readable code and think that return can be useful in branches as in the example above when the function is short for longer or more complicated functionsit might be better to have
3,780
one single return statement be prepared for critical comments if you return wherever you want an expression you will often encounter when dealing with programmingis main programor that some code is in main this is nothing particular to pythonand simply refers to that part of the program which is outside functions howevernote that the def line of functions is counted into main soin ball_function py aboveall statements outside the function are in mainand also the line def ( ) function may take no argumentsor manyin which case they are just listed within the parentheses (following the function nameand separated by comma let us illustrate take slight variation of the ball example and assume that the ball is not thrown straight upbut at an angleso that two coordinates are needed to specify its position at any time according to newton' laws (when air resistance is negligible)the vertical position is given by td : gt and the horizontal position by td we can include both these expressions in new version of our program that prints the position of the ball for chosen times assume we want to evaluate these expressions at two points in timet : and : we can pick some numbers for the initial velocity components and xname the program ball_position_xy pyand write it for example as def ( yt) acceleration of gravity return * * * ** def ( xt)return * initial_velocity_x initial_velocity_y time just pick one point in time print (initial_velocity_xtime) (initial_velocity_ytimetime pick another point in time print (initial_velocity_xtime) (initial_velocity_ytimenow we compute and print the two components for the positionfor each of the two chosen points in time notice how each of the two functions now takes two arguments running the program gives the output function may also have no return valuein which case we simply drop the return statementor it may return more than one value for examplethe two functions we just defined could alternatively have been written as onedef xy( xv yt) acceleration of gravity return *tv * * * **
3,781
basic constructions notice the two return values which are simply separated by comma when calling the function (and printing)arguments must appear in the same order as in the function definition we would then write print xy(initial_x_velocityinitial_y_velocitytimethe two returned values from the function could alternatively have been assigned to variablese as x_posy_pos xy(initial_x_velocityinitial_y_velocitytimethe variables x_pos and y_pos could then have been printed or used in other ways in the code there are possibilities for having variable number of function input and output parameters (using *args and **kwargs constructions for the argumentshoweverwe do not go further into that topic here variables that are defined inside functione in the last xy functionare local variables this means they are only known inside the function thereforeif you had accidentally used in some calculation outside the functionyou would have got an error message the variable time is defined outside the function and is therefore global variable it is known both outside and inside the function(sif you define one global and one local variableboth with the same namethe function only sees the local oneso the global variable is not affected by what happens with the local variable of the same name the arguments named in the heading of function definition are by rule local variables inside the function if you want to change the value of global variable inside functionyou need to declare the variable as global inside the function that isif the global variable was xwe would need to write global inside the function definition before we let the function change it after function executionx would then have changed value one should strive to define variables mostly where they are needed and not everywhere another very useful way of handling function parameters in pythonis by defining parameters as keyword arguments this gives default values to parameters and allows more freedom in function callssince the order and number of parameters may vary let us illustrate the use of keyword arguments with the function xy assume we defined xy as def xy(tv = = ) acceleration of gravity return *tv * * * ** heret is an ordinary or positional argumentwhereas and are keyword arguments or named arguments generallythere can be many positional arguments and many keyword argumentsbut the positional arguments must always be listed before the keyword arguments in function definition keyword arguments are given default valuesas shown here with and yboth having zero as de
3,782
fault value in scriptthe function xy may now be called in many different ways for exampleprint xy( would make xy perform the computations with and the default values ( zeroof and the two numbers returned from xy are printed to the screen if we wanted to use another initial value for ywe coulde write print xy( , = which would make xy perform the calculations with ( the default valueand when there are several positional argumentsthey have to appear in the same order as defined in the function definitionunless we explicitly use the names of these also in the function call with explicit name specification in the callany order of parameters is acceptable to illustratewe coulde call xy as print xy( = = = in any programming languageit is good habit to include little explanation of what the function is doingunless what is done by the function is obviouse when having only few simple code lines this explanation is called doc stringwhich in python should be placed just at the top of the function this explanation is meant for human who wants to understand the codeso it should say something about the purpose of the code and possibly explain the arguments and return values if needed if we do that with our xy function from abovewe may write the first lines of the function as def xy( xv yt)"""compute the and position of the ball at time ""note that other functions may be called from within other functionsand function input parameters are not required to be numbers any object will doe string variables or other functions functions are straightforwardly passed as arguments to other functionsas illustrated by the following script function_as_argument pydef sum_xy(xy)return def prod_xy(xy)return * def treat_xy(fxy)return (xyx print treat_xy(sum_xyxyprint treat_xy(prod_xyxy
3,783
basic constructions when runthis program first prints the sum of and ( )and then it prints the product ( we see that treat_xy takes function name as its first parameter inside treat_xythat function is used to actually call the function that was given as input parameter thereforeas shownwe may call treat_xy with either sum_xy or prod_xydepending on whether we want the sum or product of and to be calculated functions may also be defined within other functions it that casethey become local functionsor nested functionsknown only to the function inside which they are defined functions defined in main are referred to as global functions nested function has full access to all variables in the parent functioni the function within which it is defined short functions can be defined in compact wayusing what is known as lambda functionf lambda xyx * equivalent def (xy)return * the syntax consists of lambda followed by series of argumentscolonand some python expression resulting in an object to be returned from the function lambda functions are particularly convenient as function argumentsprint treat_xy(lambda xyx*yxyoverhead of function calls function calls have the downside of slowing down program execution usuallyit is good thing to split program into functionsbut in very computing intensive partse inside long loopsone must balance the convenience of calling function and the computational efficiency of avoiding function calls it is good rule to develop program using plenty of functions and then in later optimization stagewhen everything computes correctlyremove function calls that are quantified to slow down the code here is little example in ipython where we calculate the cpu time for doing array computations with and without helper functionin [ ]import numpy as np in [ ] np zeros( in [ ]def add(ab)return in [ ]%timeit for in range(len( )) [iadd(ii+ the slowest run took times longer than the fastest this could mean that an intermediate result is being cached loopsbest of ms per loop in [ ]%timeit for in range(len( )) [ii ( + loopsbest of ms per loop
3,784
we notice that there is some overhead in function calls the impact of the overhead reduces quickly with the amount of computational work inside the function for loops many computations are repetitive by nature and programming languages have certain loop structures to deal with this here we will present what is referred to as for loop (another kind of loop is while loopto be presented afterwardsassume you want to calculate the square of each integer from to this could be done with the following two-line program for in [ ]print ** note the colon and indentation againwhat happens when python interprets your code herefirst of allthe word for is reserved word signalling to python that for loop is wanted python then sticks to the rules covering such constructions and understands thatin the present examplethe loop should run successive times ( iterations should be done)letting the variable take on the numbers in turn during each iterationthe statement inside the loop ( print ** is carried out after each iterationi is automatically (behind the sceneupdated when the last number is reachedthe last iteration is performed and the loop is finished when executedthe program will therefore print out and the variable is often referred to as loop indexand its name (here iis choice of the programmer note thathad there been several statements within the loopthey would all be executed with the same value of (before changed in the next iterationmake sure you understand how program execution flows hereit is important in pythoninteger values specified for the loop variable are often produced by the built-in function range the function range may be called in different waysthat either explicitlyor implicitlyspecify the startstop and step ( changeof the loop variable generallya call to range reads range(startstopstepthis call makes range return the integers from (and includingstartup to (but excluding!stopin steps of step note here that stop- is the last integer included with rangethe previous example would rather read for in range( )print ** by defaultif range is called with only two parametersthese are taken to be start and stopin which case step of is understood if only single parameter is used in the call to rangethis parameter is taken to be stop the default step of
3,785
basic constructions is then used (combined with the starting at thuscalling rangefor exampleas range( would return the integers note that decreasing integers may be produced by letting start stop combined with negative step this makes it easy toe traverse arrays in either direction let us modify ball_plot py from sect to illustrate how useful for loops are if you need to traverse arrays in that example we computed the height of the ball at every milli-second during the first second of its (verticalflight and plotted the height versus time assume we want to find the maximum height during that timehow can we do it with computer programone alternative may be to compute all the thousand heightsstore them in an arrayand then run through the array to pick out the maximum the programnamed ball_max_height pymay look as follows import matplotlib pyplot as plt linspace( * * * ** initial velocity acceleration of gravity points in time interval generate all heights at this pointthe array with all the heights is ready now we need to find the largest value within largest_height [ for in range( )if [ilargest_heightlargest_height [istarting value for search print "the largest height achieved was % (largest_heightwe might also like to plot the path again just to compare plt plot( ,yplt xlabel('time ( )'plt ylabel('height ( )'plt show(there is nothing new hereexcept the for loop constructionso let us look at it in more detail as explained abovepython understands that for loop is desired when it sees the word for the range(function will produce integers fromand including up toand including the value in [ is used as the preliminary largest heightso thate the very first check that is made is testing whether [ is larger than this height if soy[ is stored as the largest height the for loop then updates to and continues to check [ ]and so on each time we find larger numberwe store it when finishedlargest_height
3,786
will contain the largest number from the array when you run the programyou get the largest height achieved was which compares favorably to the plot that pops up to implement the traversing of arrays with loops and indicesis sometimes challenging to get right you need to understand the startstop and step length choices for an indexand also how the index should enter expressions inside the loop at the same timehoweverit is something that programmers do oftenso it is important to develop the right skills on these matters having one loop inside anotherreferred to as double loopis sometimes usefule when doing linear algebra say we want to find the maximum among the numbers stored in matrix the code fragment could look like largest_number [ ][ for in range( )for in range( )if [ ][jlargest_numberlargest_number [ ][jhereall the indices ( will be covered for each value of index firsti stays fixed at while runs over all its indices theni stays fixed at while runs over all its indices againand so on sketch on piece of paper and follow the first few loop iterations by handthen you will realize how the double loop construction works using two loops is just special case of using multiple or nested loopsand utilizing more than two loops is just straightforward extension of what was shown here notehoweverthat the loop index name in multiple loops must be unique to each of the nested loops note also that each nested loop may have as many code lines as desiredboth before and after the next inner loop the vectorized computation of heights that we did in ball_plot py (sect could alternatively have been done by traversing the time array (tandfor each elementcomputing the height according to the formula gt howeverit is important to know that vectorization goes much quicker so when speed is importantvectorization is valuable use loops to compute sums one important use of loopsis to calculate sums as simple exampleassume some variable given by the mathematical expression xd ii summing up the first even numbers for some given say would typically be computed in computer program as
3,787
basic constructions for in range( + ) + * print executing this code will print the number to the screen note in particular how the accumulation variable is initialized to zero the value of then gets updated with each iteration of the loopand not until the loop is finished will have the correct value this way of building up the value is very common in programmingso make sure you understand it by simulating the code segment above by hand it is technique used with loops in any programming language while loops python also has another standard loop constructionthe while loopdoing iterations with loop index very much like the for loop to illustrate what such loop may look likewe consider another modification of ball_plot py in sect we will now change it so that it finds the time of flight for the ball assume the ball is thrown with slightly lower initial velocitysay : ms while everything else is kept unchanged since we still look at the first second of the flightthe heights at the end of the flight become negative howeverthis only means that the ball has fallen below its initial starting positioni the height where it left the handso there is no problem with that in our array we will then have series of heights which towards the end of become negative let usin program named ball_time py find the time when heights start to get negativei when the ball crosses the program could look like this from numpy import linspace linspace( * * * ** initial velocity acceleration of gravity points in time interval generate all heights find where the ball hits = while [ > + nowy[ - ]> and [ ]< so let' take the middle point in time as the approximation for when the ball hits = print " = at" *( [ - [ ]we plot the path again just for comparison import matplotlib pyplot as plt plt plot(typlt plot( * ' --'plt xlabel('time ( )'plt ylabel('height ( )'plt show(
3,788
if you type and run this program you should get = at the new thing here is the while loop only the loop (note colon and indentationwill run as long as the boolean expression [ evaluates to true note that the programmer introduced variable (the loop indexby the name iinitialized it ( before the loopand updated it ( + in the loop so for each iterationi is explicitly increased by allowing check of successive elements in the array compared to for loopthe programmer does not have to specify the number of iterations when coding while loop it simply runs until the boolean expression becomes false thusa loop index (as we have in for loopis not required furthermoreif loop index is used in while loopit is not increased automaticallyit must be done explicitly by the programmer of coursejust as in for loops and if blocksthere might be (arbitrarilymany code lines in while loop any for loop may also be implemented as while loopbut while loops are more general so not all of them can be expressed as for loop problem to be aware ofis what is usually referred to as an infinite loop in those unintentional (erroneouscasesthe boolean expression of the while test never evaluates to falseand the program can not escape the loop this is one of the most frequent errors you will experience as beginning programmer if you accidentally enter an infinite loop and the program just hangs foreverpress ctrl+ to stop the program lists and tuples alternatives to arrays we have seen that group of numbers may be stored in an array that we may treat as wholeor element by element in pythonthere is another way of organizing data that actually is much usedat least in non-numerical contextsand that is construction called list list is quite similar to an array in many waysbut there are pros and cons to consider for examplethe number of elements in list is allowed to changewhereas arrays have fixed length that must be known at the time of memory allocation elements in list can be of different typei you may mix integersfloats and stringswhereas elements in an array must be of the same type in generallists provide more flexibility than do arrays on the other handarrays give faster computations than listsmaking arrays the prime choice unless the flexibility of lists is needed arrays also require less memory use and there is lot of ready-made code for various mathematical operations vectorization requires arrays to be used the range(function that we used above in our for loop actually returns list if you for example write range( at the prompt in ipythonyou get [ in returni list with numbers in for loopthe line for in range[ makes take on each of the numbers in turnas we saw above writinge range( )gives list by the name xcontaining those five numbers these numbers may now be accessed ( as [ ]which contains the number and used in computations just as we saw for array elements as with arraysindices run from to when is the number of elements in list you may convert list to an array by array(
3,789
basic constructions list may also be created by simply writinge ['hello' giving list where [ contains the string hellox[ contains the integer etc we may add and/or delete elements anywhere in the list as shown in the following example ['hello' insert( - then becomes [- 'hello' del [ then becomes [- 'hello' append( then becomes [- 'hello' note the ways of writing the different operations here using append(will always increase the list at the end if you likeyou may create an empty list as [before you enter loop which appends element by element if you need to know the length of the listyou get the number of elements from len( )which in our case is after appending above this function is handy if you want to traverse all list elements by indexsince range(len( )gives you all legal indices note that there are many more operations on lists possible than shown here previouslywe saw how for loop may run over array elements when we want to do the same with list in pythonwe may do it as this little example showsx ['hello' for in xprint ' element' print 'this was all the elements in the list xthis is how it usually is done in pythonand we see that runs over the elements of directlyavoiding the need for indexing be awarehoweverthat when loops are written like thisyou can not change any element in by "changinge that iswriting + will not change anything in xsince can only be used to read (as opposed to overwritethe list elements there is special construct in python that allows you to run through all elements of listdo the same operation on eachand store the new elements in another list it is referred to as list comprehension and may be demonstrated as follows list_ [ list_ [ * for in list_ this will produce new list by the name list_ containing the elements and in that order notice the syntax within the brackets for list_ for in list_ signals that is to successively be each of the list elements in list_ and for each ecreate the next element in list_ by doing * more generallythe syntax may be written as list_ [ (efor in list_ where (emeans some expression involving
3,790
in some casesit is required to run through (or morelists at the same time python has handy function called zip for this purpose an example of how to use zip is provided in the code file_handling py below we should also briefly mention about tupleswhich are very much like liststhe main difference being that tuples cannot be changed to freshmanit may seem strange that such "constant listscould ever be preferable over lists howeverthe property of being constant is good safeguard against unintentional changes alsoit is quicker for python to handle data in tuple than in listwhich contributes to faster code with the data from abovewe may create tuple and print the content by writing ('hello' for in xprint ' element' print 'this was all the elements in the tuple xtrying insert or append for the tuple gives an error message (because it cannot be changed)stating that the tuple object has no such attribute reading from and writing to files input data for program often come from files and the results of the computations are often written to file to illustrate basic file handlingwe consider an example where we read and coordinates from two columns in fileapply function to the coordinatesand write the results to new two-column data file the first line of the input file is heading that we can just skipx and coordinates the relevant python lines for reading the numbers and writing out similar file are given in the file file_handling py filename 'tmp datinfile open(filename' 'open file for reading line infile readline(read first line read and coordinates from the file and store in lists [ [for line in infilewords line split(split line into words append(float(words[ ]) append(float(words[ ])infile close(
3,791
basic constructions transform coordinates from math import log def ( )return log(yfor in range(len( )) [if( [ ]write out and to two-column file filename 'tmp_out datoutfile open(filename' 'open file for writing outfile write(' and coordinates\ 'for xiyi in zip(xy)outfile write('% % \ (xiyi)outfile close(such file with comment line and numbers in tabular format is very common so numpy has functionality to ease reading and writing here is the same example using the loadtxt and savetxt functions in numpy for tabular data (file file_handling_numpy py)filename 'tmp datimport numpy data numpy loadtxt(filenamecomments='#' data[:, data[:, data[:, numpy log(yinsert transformed back in array filename 'tmp_out datfilename 'tmp_out datoutfile open(filename' 'open file for writing outfile write(' and coordinates\ 'numpy savetxt(outfiledatafmt='% ' exercises exercise errors with colonindentetc write the program ball_function py as given in the text and confirm that the program runs correctly then save copy of the program and use that program during the following error testing you are supposed to introduce errors in the codeone by one for each error introducedsave and run the programand comment how well python' response corresponds to the actual error when you are finished with one errorre-set the program to correct behavior (and check that it works!before moving on to the next error achange the first line from def ( )to def ( ) remove the colon bremove the indent in front of the statement inside the function yi shift the text four spaces to the left
3,792
exercises cnow let the statement inside the function have an indent of three spaces (while the remaining two lines of the function have fourdremove the left parenthesis in the first statement def ( )echange the first line of the function definition from def ( )to def (): remove the parameter fchange the first occurrence of the statement print (timeto print (filenameerrors_colon_indent_etc py exercise compare integers and explain brieflyin your own wordswhat the following program does input('give an integer ' input('give an integer 'if bprint " is the smallest of the two numberselif =bprint " and are equalelseprint " is the largest of the two numbersproceed by writing the programand then run it few times with different values for and to confirm that it works as intended in particularchoose combinations for and so that all three branches of the if construction get tested filenamecompare_a_and_b py exercise functions for circumference and area of circle write program that takes circle radius as input from the user and then computes the circumference and area of the circle implement the computations of and as two separate functions that each takes as input parameter print and to the screen along with an appropriate text run the program with and confirm that you get the right answer filenamefunctions_circumference_area py exercise function for area of rectangle write program that computes the area bc of rectangle the values of and should be user input to the program alsowrite the area computation as function that takes and as input parameters and returns the computed area let the program print the result to screen along with an appropriate text run the program with and to confirm correct program behavior filenamefunction_area_rectangle py exercise area of polygon one of the most important mathematical problems through all times has been to find the area of polygonespecially because real estate areas often had the shape of polygonsand it was necessary to pay tax for the area we have polygon as depicted below
3,793
basic constructions the vertices ("corners"of the polygon have coordinates / /:xn yn /numbered either in clockwise or counter clockwise fashion the area of the polygon can amazingly be computed by just knowing the boundary coordinates xn yn xn yn xn yn / write function polyarea(xythat takes two coordinate arrays with the vertices as arguments and returns the area assume that and are either lists or arrays test the function on trianglea quadrilateraland pentagon where you can calculate the area by alternative methods for comparison hint since python lists and arrays has as their first indexit is wise to rewrite the mathematical formula in terms of vertex coordinates numbered as xn and yn filenamepolyarea py exercise average of integers write program that gets an integer from the user and computes the average of all integers the computation should be done in function that takes as input parameter print the result to the screen with an appropriate text run the program with and confirm that you get the correct answer filenameaverage_ _to_n py
3,794
exercises exercise while loop with errors assume some program has been written for the task of adding all integers some_number while some_number + print some_number aidentify the errors in the program by just reading the code and simulating the program by hand bwrite new version of the program with errors corrected run this program and confirm that it gives the correct output filenamewhile_loop_errors py exercise area of rectangle versus circle consider one circle and one rectangle the circle has radius : the rectangle has sides and bbut only is known from the outset let : and write program that uses while loop to find the largest possible integer that gives rectangle area smaller thanbut as close as possible tothe area of the circle run the program and confirm that it gives the right answer (which is filenamearea_rectangle_vs_circle py exercise find crossing points of two graphs consider two functions xd and xd on the interval oe write program thatby trial and errorfinds approximately for which values of the two graphs crossi xd xdo this by considering equally distributed points on the intervalat each point checking whether jf / / where is some small number let and be user input to the program and let the result be printed to screen run your program with and : explain the output from the program finallytry also other values of keeping the value of fixed explain your observations filenamecrossing_ _graphs py exercise sort array with numbers the import statement from random import will give access to function uniform that may be used to draw (pseudo-)random numbers from uniform distribution between two numbers (inclusiveand (inclusivefor examplewriting uniform( , makes float value larger thanor equal to and smaller thanor equal to write script that generates an array of random numbers between and the program should then sort the array so that numbers appear in increasing order let the program make formatted print of the array to the screen both before and after sorting the printouts should appear on the screen so that comparison is made easy confirm that the array has been sorted correctly filenamesort_numbers py
3,795
basic constructions exercise compute up through historygreat minds have developed different computational schemes for the number we will here consider two such schemesone by leibniz ( )and one by euler ( the scheme by leibniz may be written kd while one form of the euler scheme may appear as dt kd if only the first terms of each sum are used as an approximation to each modified scheme will have computed with some error write program that takes as input from the userand plots the error development with both schemes as the number of iterations approaches your program should also print out the final error achieved with both schemesi when the number of terms is run the program with and explain briefly what the graphs show filenamecompute_pi py exercise compute combinations of sets consider an id number consisting of two letters and three digitse re how many different numbers can we haveand how can program generate all these combinationsif collection of things can have variations of the first thingm of the second and so onthe total number of variations of the collection equals mn in particularthe id number exemplified above can have     variations to generate all the combinationswe must have five nested for loops the first two run over all letters aband so on to zwhile the next three run over all digits to convince yourself about this resultstart out with an id number on the form where the first part can vary among aband cand the digit can be among or we must start with and combine it with and then continue with bcombined with and and finally combine with and double for loop does the work ain deck of cardseach card is combination of rank and suit there are ranksace ( ) jack ( )queen ( )king ( )and four suitsclubs ( )diamonds ( )hearts ( )and spades (sa typical card may be write statements that generate deck of cardsi all the combinations cac and so on to sk ba vehicle registration number is on the form de where the letters vary from to and the digits from to write statements that compute all the possible registration numbers and stores them in list
3,796
exercises cgenerate all the combinations of throwing two dice (the number of eyes can vary from to count how many combinations where the sum of the eyes equals filenamecombine_sets py exercise frequency of random numbers write program that takes positive integer as input and then draws random integers in the interval oe (both ends inclusivein the programcount how many of the numbersm that equal and write out the fraction = alsoprint all the random numbers to the screen so that you can check for yourself that the counting is correct run the program with small value for ( to confirm that it works as intended hint use random randint( , to draw random integer between and filenamecount_random_numbers py remarks for large this program computes the probability = of getting six eyes when throwing die exercise game consider some game where each participant draws series of random integers evenly distributed from and with the aim of getting the sum as close as possible to but not larger than you are out of the game if the sum passes after each drawyou are told the number and your total sumand are asked whether you want another draw or not the one coming closest to is the winner implement this game in program hint use random randint( , to draw random integers in oe filenamegame_ py exercise linear interpolation some measurements yi (given below)of quantity have been collected regularlyonce every minuteat times ti ii we want to find the value in between the measurementse at : min computing such values is called interpolation let your program use linear interpolation to compute between two consecutive measurements find such that ti ti find mathematical expression for the straight line that goes through the points iyi and yi compute the value by inserting the user' time value in the expression for the straight line aimplement the linear interpolation technique in function that takes an array with the yi measurements as inputtogether with some time tand returns the interpolated value at time
3,797
basic constructions bwrite another function with loop where the user is asked for time on the interval oe and the corresponding (interpolatedy value is written to the screen the loop is terminated when the user gives negative time cuse the following measurements : : : : : corresponding to times (min)and compute interpolated values at : and : min perform separate hand calculations to check that the output from the program is correct filenamelinear_interpolation py exercise test straight line requirement assume the straight line function xd write script that tests the "point-slopeform for this line as follows within chosen interval on the -axis (for examplefor between and )randomly pick points on the line and check if the following requirement is fulfilled for each pointf xi cd axi where is the slope of the line and defines fixed point cf /on the line let here filenametest_straight_line py exercise fit straight line to data assume some measurements yi have been collectedonce every second your task is to write program that fits straight line to those data amake function that computes the error between the straight line xd axcb and the measurementsed axi yi / bmake function with loop where you give and bthe corresponding value of is written to the screenand plot of the straight line xd ax together with the discrete measurements is shown hint to make the plotting from the loop to workyou may have to insert from matplotlib pylab import at the top of the script and also add show(after the plot command in the loop cgiven the measurements : : : : : at times use the function in bto interactively search for and such that is minimized filenamefit_straight_line py remarks fitting straight line to measured data points is very common task the manual search procedure in ccan be automated by using mathematical method called the method of least squares
3,798
exercises exercise fit sines to straight line lot of technologyespecially most types of digital audio devices for processing soundis based on representing signal of time as sum of sine functions say the signal is some function ton the interval oe( more general interval oeabcan easily be treatedbut leads to slightly more complicated formulasinstead of working with tdirectlywe approximate by the sum sn td bn sin nt/( nd where the coefficients bn must be adjusted such that sn tis good approximation to twe shall in this exercise adjust bn by trial-and-error process amake function sinesum(tbthat returns sn /given the coefficients bn in an array and time coordinates in an array note that if is an arraythe return value is also an array bwrite function test_sinesum(that calls sinesum(tbin aand determines if the function computes test case correctly as test caselet be an array with values = and = choose and and compute sn tby hand to get reference values cmake function plot_compare(fnmthat plots the original function ttogether with the sum of sines sn /so that the quality of the approximation sn tcan be examined visually the argument is python function implementing / is the number of terms in the sum sn /and is the number of uniformly distributed coordinates used to plot and sn dwrite function error(bfmthat returns mathematical measure of the error in sn tas an approximation to /ed sx ti sn ti // where the ti values are uniformly distributed coordinates on oethe array holds the coefficients in sn and is python function implementing the mathematical function temake function trial(fnfor interactively giving bn values and getting plot on the screen where the resulting sn tis plotted together with tthe error in the approximation should also be computed as indicated in dthe argument is python function for tand is the number of terms in the sum sn tthe trial function can run loop where the user is asked for the bn values in each pass of the loop and the corresponding plot is shown you must find way to terminate the loop when the experiments are over use = in the calls to plot_compare and error hint to make this part of your program workyou may have to insert from matplotlib pylab import at the top and also add show(after the plot command in the loop
3,799
basic constructions fchoose tto be straight line td on oecall trial( and try to find through experimentation some values and such that the sum of sines sn tis good approximation to the straight line gnow we shall try to automate the procedure in fwrite function that has three nested loops over values of and let each loop cover the interval oe in steps of for each combination of and the error in the approximation sn should be computed use this to findand printthe smallest error and the corresponding values of and let the program also plot and the approximation sn corresponding to the smallest error filenamefit_sines py remarks the function sn xis special case of what is called fourier series at the beginning of the th centuryjoseph fourier ( - showed that any function can be approximated analytically by sum of cosines and sines the approximation improves as the number of terms ( is increased fourier series are very important throughout science and engineering today (afinding the coefficients bn is solved much more accurately in exercise by procedure that also requires much less human and computer work(bin real applicationsf tis not known as continuous functionbut function values of tare provided for examplein digital sound applicationsmusic in cd-quality wav file is signal with , samples of the corresponding analog signal tper second exercise count occurrences of string in string in the analysis of genes one encounters many problem settings involving searching for certain combinations of letters in long string for examplewe may have string like gene 'agtcaatggaataggccaagcgaatatttgggctaccawe may traverse this stringletter by letterby the for loop for letter in gene the length of the string is given by len(gene)so an alternative traversal over an index is for in range(len(gene)letter number is reached through gene[ ]and substring from index up tobut not including jis created by gene[ :jawrite function freq(lettertextthat returns the frequency of the letter letter in the string texti the number of occurrences of letter divided by the length of text call the function to determine the frequency of and in the gene string above compute the frequency by hand too bwrite function pairs(lettertextthat counts how many times pair of the letter letter ( ggoccurs within the string text use the function to determine how many times the pair aa appears in the string gene above perform manual counting too to check the answer