Computing with Formulas
The First Programming Encounter: a Formula
- Using a Program as a Calculator
- About Programs and Programming
- Tools for Writing Programs
- Writing and Running Your First Python Program
- Warning About Typing Program Text
- Verifying the Result
- Using Variables
- Names of Variables
- Reserved Words in Python
- Comments
- Formatting Text and Numbers
Use the same variable names in the program as in the mathematical description of the problem you want to solve. The program is located in the folder fileball_print1.pyin thesrc/formulas in the collection of programs associated with this book.
Computer Science Glossary
A computer program must have correct syntax, which means that the text in the program must follow the strict rules of the computer language to construct statements. All input data must be assigned values in the program before the output can be calculated.
Another Formula: Celsius-Fahrenheit Conversion
- Potential Error: Integer Division
- Objects in Python When we writeWhen we write
- Avoiding Integer Division
- Arithmetic Operators and Precedence
In this book, we will often develop several trial versions of a program, but remove the version number in the final version of the program. In the first two lines, one of the operands is written as a decimal number, implying a floating object and thus floating division.
Evaluating Standard Mathematical Functions
- Example: Using the Square Root Function
- Example: Computing with sinh x
- A First Glimpse of Rounding Errors
It is generally not recommended to import more functions than those that are really used in the program. Import with new names Imported modules and functions can be given new names in the import statement, e.g.
Interactive Computing
- Using the Python Shell
- Type Conversion
- IPython
Once you use Python interactively as explained in the next section, you will encounter rounding errors quite often. In the statement C = float(C) we create a new object from the original object referenced by the name C and associate it with the same name C.
Complex Numbers
- Complex Arithmetics in Python
- Complex Functions in Python
- Unified Treatment of Complex and Real Functions
A similar module, cmath, defines functions that take a complex number as an argument and return a complex number as a result. It would be nice to have functions that return float object if the result is a real number and a complex object if the result is a complex number.
Symbolic Computing
- Basic Differentiation and Integration
- Equation Solving
- Taylor Series and More
A very handy feature of SymPy is that symbolic expressions can be turned into regular Python vialambdify functions. A linear equation defined by an expression that is zero can be solved by solve (e, t) if there is an unknown (symbol) in the equation.
Summary .1 Chapter Topics
- Example: Trajectory of a Ball
- About Typesetting Conventions in This Book
Complex numbers The values of complex numbers are written as (X+Yj), where X is the value of the real part and Y is the value of the imaginary part. The rest of the program should be self-explanatory at this stage in the book.
Exercises
If the answer to the exercise is a Python program, you must save the program in a myexer.py file. The test run shows that the program runs and produces correct results in a test case.
Compute 1+1
Beginners often underestimate the amount of work required in the first and third stages and instead try to complete the second stage (ie write the program) as quickly as possible. When you submit exercises to teaching assistants, there is often a request to insert atrial control at the end of the code.
Write a Hello World program
Derive and compute a formula
Convert from meters to British length units
Compute the mass of various substances
Compute the growth of money in a bank
Find error(s) in a program
Type in programs and debug them
Evaluate a Gaussian function The bell-shaped Gaussian function,
Compute the air resistance on a football
How to cook the perfect egg
Derive the trajectory of a ball
Use the program to calculate the forces on the ball for a hard kick, V D120 km=h and for a soft kick, V D 30 km=h (it's easy to mix up inconsistent units, so be sure to calculate with V expressed in m= s) . Also show that if we eliminate, we end up with the relation (1.6) between thexandy coordinates of the ball.
Find errors in the coding of formulas
If we assume that gravity is the only significant force on the ball, Fx D 0 and FyD mg.
Explain why a program does not work Figure out why the following program does not work
Find errors in Python statements
Find errors in the coding of a formula Given a quadratic equation,
Find errors in a program What is the problem in the following program?
Loops and Lists
While Loops
- A Naive Solution
- While Loops
- Boolean Expressions
- Loop Implementation of a Sum
The purpose of each pass of the loop is to calculate a new expression and add it to s. Then we test the loop condition: 3 < 25 is True, so we re-enter the loop block.
Lists
- Basic List Operations
- For Loops
To access the element with index 3, i.e. the fourth element in the list, we can write C[3]. In the first pass of the loop, Crefer refers to the first element in the list of degrees, ie. to an intobject that has a value of 0.
Alternative Implementations with Lists and Loops
- While Loop Implementation of a for Loop
- The Range Construction
- For Loops with List Indices
- Changing List Elements
- List Comprehension
- Traversing Multiple Lists Simultaneously
Instead of adding new elements to the lists, we can start with lists of the right size, containing zeros, and then index the lists to fill in the right values. The problem is that it is a regular variable that refers to a list element in the loop, but when we do += 5, we go to a new float object (c+5).
Nested Lists
- A table as a List of Rows or Columns
- Printing Objects
- Extracting Sublists
- Traversing Nested Lists
In the general case, we may have players, and some may have played the game a large number of times, potentially making a large nested list. To visit each of the elements in the list, we use as many nested forloops as there are indices.
Tuples
Tuples are often used in Python software, which you will definitely make use of, so you need to know this data type. There is also a fourth argument which is important for a data type called dictionaries (introduced in Sect.6.1): tuples can be used as keys in dictionaries, while lists cannot.
Summary .1 Chapter Topics.1Chapter Topics
- Example: Analyzing List Data
- How to Find More Python Information
Tuples A tuple can be thought of as a constant list: changes to the contents of the tuple are not allowed. The list in each line contains the number of hours of sunshine for each of the 12 months of the year.
Exercises
Make a Fahrenheit-Celsius conversion table
Generate an approximate Fahrenheit-Celsius conversion table Many people use an approximate formula for quickly converting Fahrenheit (F ) to
Generate odd numbers
Compute the sum of the first n integers
Compute energy levels in an atom
The energy released when an electron moves from levelni to levelnf is given by .. Add instructions to the program from a) so that it prints a second, nicely formatted table where the cell in columni and rowf contains the energy released when a electron moves from energy levelito levelf, fori; f D1;.
Generate equally spaced coordinates
Make a table of values from a formula
Store values from a formula in lists
Simulate operations on lists by hand You are given the following program
Compute a mathematical sum
Replace a while loop by a for loop
Simulate a program by hand
Explore Python documentation
Store data in lists
Store data in a nested list
Values of boolean expressions
Explore round-off errors from a large number of inverse operations
Explore what zero can be on a computer Type in the following code and run it
Compare two real numbers with a tolerance Run the following program
The lesson learned from this program is that one should never directly compare two floating-point objects with a == bora != b, because rounding errors quickly cause two identical mathematical values to be different on a computer. The function time in the time module returns the number of seconds since a given date (called the Epoch, which is January 1, 1970 on many types of computers).
Explore problems with inaccurate indentation
Now copy the code segment and change the
Explore punctuation in Python programs
Investigate a for loop over a changing list
Functions and Branching
Functions
- Mathematical Functions as Python Functions
- Understanding the Program Flow
- Local and Global Variables
- Multiple Arguments
- Function Argument or Global Variable?
- Beyond Mathematical Functions
- Multiple Return Values
- Computing Sums
- Functions with No Return Values
- Keyword Arguments
- Doc Strings
- Functions as Arguments to Functions
- The Main Program
- Lambda Functions
On the contrary, the variables defined outside the function, likes1,s2 and c1 in the above session, are global variables. The keyword arguments must always come after the positional arguments in the function definition.
Branching
- If-else Blocks
- Inline if Tests
A well-known programming rule is to avoid multiple return statements in a function - there should only be one return at the end. The traditional if-else construct with indented blocks cannot be used within lambda functions because it is not simply an expression (lambda functions cannot have statements within them, only a single expression).
Mixing Loops, Branching, and Functions in Bioinformatics Examples
- Counting Letters in DNA Strings
- Efficiency Assessment
- Verifying the Implementations
List Iteration The simplest solution is to iterate through the letters in the string, test whether the current letter is equal to the desired letter, and if so, increment a counter. The full suite of functions presented above, including the timings and tests, can be found in the filecount.py.
Summary .1 Chapter Topics
- Example: Numerical Integration Problem An integralProblemAn integral
It is a good habit to write such test functions, since the execution of all tests in all files can be fully automated. The order of the keyword arguments can be arbitrary, and the keyword arguments not listed in the call are given their default values according to the function definition.
Exercises
Implement a simple mathematical function Implement the mathematical function
Implement a simple mathematical function with a parameter Let us extend the function g.t/ in Exercise 3.1 to
Explain how a program works Explain how the following program works
Write a Fahrenheit-Celsius conversion functions The formula for converting Fahrenheit degrees to Celsius reads
Given a test function, write the function Here is a test function
Evaluate a sum and write a test function
Implement the sum function
Compute a polynomial via a product
Integrate a function by the Trapezoidal rule
Run the examples from b) with nD10. e) Write a test function test_trapezint() to check the execution of the function trapezint d). The reason is that f .xiC1/ is evaluated twice, first in term i and then asf .xi/in termiC1.
Derive the general Midpoint integration rule
The formula can be further developed to avoid unnecessary evaluations of .xiC1/ resulting in the default form. How do the errors in the midpoint rule compare to those in the trapezoidal rule for nD1 and nD10.
Make an adaptive Trapezoidal rule
Implement this formula in a Python function midpointint(f, a, b, n) and test the function against the examples in Exercise 3.11b. Hint Then compute accordingly as explained above and call trapezoid(f, a, b, n) from Exercise 3.11. b) Apply the function to calculate the integrals from Exercise 3.11b.
Simulate a program by hand
With the calculated estimate of maxjf00.x/j we can find hfrom setting the right side of (3.13) equal to the desired tolerance:. D: Solution with respect to give. With nD.ba/= we then have that corresponds to the desired accuracy. a) Create a Python function adaptive_trapezint(f, a, b, eps=1E-5) for.
Debug a given test function Given a Python function
Tip If you're having trouble understanding function calls and local versus global variables, paste the code into the Online Python Tutor9 and step through the code to get a better explanation of what's happening.
Compute the area of an arbitrary triangle
Compute the length of a path
Compute the area of a polygon
Approximate a function by a sum of sines We consider the piecewise constant function
Implement a Gaussian function
Wrap a formula in a function
Write a function for numerical differentiation The formula
Implement the factorial function The factorial of n is written as nŠ and defined as
Find the max and min values of a function
Find the max and min elements in a list
Implement the Heaviside function
Implement a smoothed Heaviside function
Implement an indicator function
Implement a piecewise constant function
Apply indicator functions
Test your understanding of branching Consider the following code
Simulate nested loops by hand
You can use a debugger, see Sect.F.1, or the Online Python Tutor10, see Sect.3.1.2, to determine what happens as you step through the code.
Rewrite a mathematical function
You can use a debugger, see Sect.F.1, or theOnline Python Tutor10, see Sect.3.1.2, to check what happens when you step through the code. a) Create a Python function for computingC.xIn/. Hint Representercj of a variable term, make updatesterm = -term*.. inside aforloop, and accumulate the term variable in a variable for the sum. Let the x values run down the rows and then the values to the right in the columns.
Use None in keyword arguments
Write a sort function for a list of 4-tuples
However, in the present case, each element is a 4-tuple, and the default sorting of such 4-tuples results in a list of the stars in alphabetical order. In the present case, and only 4 tuples, so we need to make the comparison between the correct elements in and b.
Find pairs of characters
A key feature of the Faster construct is to provide akeyargument to sort to filter the relevant part of the object to be sorted.
Resolve a problem with a function Consider the following interactive session
Determine the types of some objects
Find an error in a program For the formula
Simulate the program flow by hand, use the debugger to step from line to line, or use the Online Python Tutor.
User Input and Error Handling
Asking Questions and Reading Answers
- Reading Keyboard Input
One of the simplest ways to get data into a program is to ask the user a question, let the user type an answer, and then read the text in that answer into a variable in the program. In general, raw_inputfunction takes a string as an argument, displays that string in a terminal window, waits for the user to press the Return key, and then returns a string object containing the sequence of characters the user typed.
Reading from the Command Line
- Providing Input on the Command Line
- A Variable Number of Command-Line Arguments
- More on Command-Line Arguments
For example, when you type -s -t to list the files in the current folder, you run the programs with two command-line arguments: -sand-t. Similarly, cp -r my new for copying a treemy folder to a new folder treenewinton thecpprogram with three command-line arguments: -r(for recursively copying files), my, andnew.
Turning User Text into Live Objects
- The Magic Eval Function
- The Magic Exec Function
- Turning String Expressions into Functions
Supplying cos(x) as the first command line argument creates a need to have cos define, so that's why we import all functions from the math module. Suppose the user can write a formula as input to the program, available to us in the form of a string object.
Option-Value Pairs on the Command Line
- Basic Usage of the Argparse Module
- Mathematical Expressions as Values
Python has a flexible and powerful module argparse for reading (parsing) option value pairs on the command line. Values on the command line involving mathematical symbols and functions, say –v0 'pi/2', pose a problem with the code example above.
Reading Data from File
- Reading a File Line by Line
- Alternative Ways of Reading a File
- Reading a Mixture of Text and Numbers
Note that the first line in the file is just a comment line and we don't care. The loop over the lines in the file will then start from the next (second) line.
Writing Data to File
- Example: Writing a Table to File
This is more advanced code, but understanding what's going on is a good test of understanding nested list indexing and list comprehension. Many files used in scientific calculations have such a format, but many files are also more complicated.