scientific programming in python - stem2 · scientific programming in python james d emery last...

77
Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints for Installing Python 2.6 on a Windows XP System . . . 5 2.2 Hints for Installing and Running Python on the Windows 7 Machine at the Trailside Center ................. 6 2.3 Hints for Running Python on a Windows 10 Machine at the Johnson County Maker Space .................. 6 2.4 Hints for a Vista Machine Running Windows 7 ......... 7 2.5 Hints for Running Python on a Macintosh OS10 System ... 7 3 Some Differences Between Python 2 and Python 3 7 3.1 Running Python 3 on the Command Line of the Raspberry Pi 8 4 Introduction 8 4.1 Using Python Interactively .................... 9 4.2 Example .............................. 11 4.3 Example: Writing Function Points to a File .......... 14 4.4 Example: Greatest Common Divisor .............. 14 4.4.1 GCD Algorithm Proof .................. 17 4.5 Adding Rational Numbers .................... 17 4.6 Example: Solar Heating, Using Command Line Arguments . . 20 4.7 Example: Electric Water Heating ................ 21 1

Upload: others

Post on 04-Oct-2019

49 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

Scientific Programming in Python

James D Emery

Last Modified: 2/17/18

Contents

1 Preface 3

2 Installing and Running Python 42.1 Hints for Installing Python 2.6 on a Windows XP System . . . 52.2 Hints for Installing and Running Python on the Windows 7

Machine at the Trailside Center . . . . . . . . . . . . . . . . . 62.3 Hints for Running Python on a Windows 10 Machine at the

Johnson County Maker Space . . . . . . . . . . . . . . . . . . 62.4 Hints for a Vista Machine Running Windows 7 . . . . . . . . . 72.5 Hints for Running Python on a Macintosh OS10 System . . . 7

3 Some Differences Between Python 2 and Python 3 73.1 Running Python 3 on the Command Line of the Raspberry Pi 8

4 Introduction 84.1 Using Python Interactively . . . . . . . . . . . . . . . . . . . . 94.2 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114.3 Example: Writing Function Points to a File . . . . . . . . . . 144.4 Example: Greatest Common Divisor . . . . . . . . . . . . . . 14

4.4.1 GCD Algorithm Proof . . . . . . . . . . . . . . . . . . 174.5 Adding Rational Numbers . . . . . . . . . . . . . . . . . . . . 174.6 Example: Solar Heating, Using Command Line Arguments . . 204.7 Example: Electric Water Heating . . . . . . . . . . . . . . . . 21

1

Page 2: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

4.8 Example: Converting degrees, minutes, seconds to a decimalnumber, using Command Line Arguments . . . . . . . . . . . 22

4.9 Example: Reading points from a file . . . . . . . . . . . . . . 234.10 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

4.10.1 reversefile.py . . . . . . . . . . . . . . . . . . . . . . . 274.10.2 Using Program reversefile.py . . . . . . . . . . . . . . . 284.10.3 Functions for Stripping Strings . . . . . . . . . . . . . 294.10.4 Partitioning Strings . . . . . . . . . . . . . . . . . . . . 31

4.11 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324.12 Functions and Scope . . . . . . . . . . . . . . . . . . . . . . . 32

4.12.1 The Scope of Variables . . . . . . . . . . . . . . . . . . 324.13 Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

4.13.1 My Modulo Program mod.py . . . . . . . . . . . . . . 334.13.2 System Function sys.maxint . . . . . . . . . . . . . . . 354.13.3 Program for Prime Numbers from Python Tutorial . . 364.13.4 Program for Fibonaccii Sequence From Python Tutorial 37

4.14 A List of some Python Commands and Their Use . . . . . . . 374.15 Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394.16 Formatting Output . . . . . . . . . . . . . . . . . . . . . . . . 404.17 Creating a Module . . . . . . . . . . . . . . . . . . . . . . . . 414.18 Using Eval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424.19 Object Oriented Programming Example . . . . . . . . . . . . 434.20 Operations on the Bytes of a File . . . . . . . . . . . . . . . . 444.21 A Matrix Class . . . . . . . . . . . . . . . . . . . . . . . . . . 454.22 Functions With a Variable Number of Arguments . . . . . . . 574.23 Class Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . 584.24 The Module Search Path . . . . . . . . . . . . . . . . . . . . . 584.25 Google Python Tutorial . . . . . . . . . . . . . . . . . . . . . 584.26 Computing the Matrix Inverse Using Gaussian Elimination . . 584.27 Examples Using Matrices . . . . . . . . . . . . . . . . . . . . . 644.28 Python Exercises . . . . . . . . . . . . . . . . . . . . . . . . . 654.29 Python References . . . . . . . . . . . . . . . . . . . . . . . . 73

5 Introduction2 73

6 Reading and Writing files 74

2

Page 3: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

7 Random Numbers 74

8 Python System Path 74

9 Bibliography 75

10 Index 77

List of Figures

1 Function Plotting: The function plotted here is f(x) =cos3(x). It was created with the sequence of programs write-func.py, a Python program to generate function points, pts2eg.c,a C program to create an eg graphics file, pltax.c, a C pro-gram to add axes to the plot, and eg2ps.c, a C program toconvert from eg to postscript. These can all be put in a singleunix script file, or in a single windows batch file. The finalfile is beautifully displayed with Ghostview, and converted topdf with Acrobat distiller or with the ps2pdf program, whichcomes with MikTex, or is installed on Linux systems, if TeX isinstalled. A couple of other useful programs here are pltc.ftn, aFortran Program to create an eg graphics file, and pltmerge.c,a C program to merge together eg files. . . . . . . . . . . . . . 12

1 Preface

There are not many choices in choosing a good programming language forpresenting Scientific Programming and Computing. Fortran was created forScientific Programming, a long long time ago, and I still use it. The firstcompiler was written for Fortran. Fortran has been modernized many times,while keeping the language somewhat compatible with earlier versions. Butthe latest version might be a bit hard (or expensive) to come by for personalcomputers. It is still widely used in science and engineering and for program-ming supercomputers. There is however a free version of a modern fortrancompiler.

3

Page 4: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

Guido van Rossum (born 31 January[5] 1956), is a Dutch programmerwho is the author of the Python programming language.

In teaching a class on Scientific Programming I chose to use Python. It isan interpreted language rather than a compiled language, so programs are notstand alone, but require an interpreter. Interpreters seem to change rapidly,so that running a program at a later date might require an interpreter thatno longer exists. There are a lot of things I like about the language, anda few that I don’t like at all. I detest using tab characters for alignmentbecause they are invisible. Version 2 and version 3 are incompatible. Thisis very irritating. Still I chose Python. Python is built into the operatingsystem for many computers, Unix computers and Macintosh. This documentwas written for version 2.6 of Python. Scientific Computing should be doneusing the command line. Graphical User Interfaces are invaluable for manycomputing tasks, but I think it is a giant mistake to make them the primarycomputer interface. Among other things, it makes computer users computerstupid.

So Scientific Computing should be done on a system with a command lineinterface. Thus perhaps a good choice for learning Scientific Programmingand Python is to use the Raspberry Pi, which was constructed to be a cheapcomputer, and a computer for teaching science and giving an understandingof computing itself. It had in mind especially young people, and those withnot yet dead brains in general.

Writing user manuals for computer languages and applications is quitedifficult and tedious, so one might have to consult many books and guidesto get complete detailed coverage. However, by learning a few of the majorfacts, you can get quite far. The best way to learn is to try out exampleprograms, and make some changes to see what happens.

This is probably not a good technique for learning medicine.

2 Installing and Running Python

Versions of Python can be downloaded for free for Windows system. Onmany other computers Python is natively installed. I recommend gettingeither version 2.6 or 2.7, rather than one of the 3 versions. Versions 2 and3 have some incompatibilities, including the fact that some of the moduleshave not been updated to version 3, but I don’t really have much knowledge

4

Page 5: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

about the incompatibilities.

2.1 Hints for Installing Python 2.6 on a Windows XPSystem

See my document Python Programming, python.tex, python.pdf. On mymain machine, the installation file called python-e2.6.4.msi, is containedin directory

C:\scitools\python2.6.4

This directory also contains a documentation file:

Volume in drive C has no label.

Volume Serial Number is 8C1E-DA95

Directory of C:\scitools\python2.6.4

05/14/2016 08:41 AM <DIR> .

05/14/2016 08:41 AM <DIR> ..

05/14/2016 08:41 AM 0 out5

01/20/2010 02:51 PM 16 outzzz1

01/20/2010 02:51 PM 20 outzzz2

12/11/2009 11:27 PM 9,092,317 python-2.6.4-docs-pdf-letter.zip

12/11/2009 11:34 PM 14,890,496 python-2.6.4.msi

5 File(s) 23,982,849 bytes

2 Dir(s) 27,915,841,536 bytes free

To install type the file name python-2.6.4.msi, which creates a directorycalled python26 containing the executable file, and which was a version olderthen the version 3.0, which has the latest version then, but which was at thattime somewhat incompatible with older 2 versions of python?

After Python version 26 is installed onWindows, add directory python26to the path variable for one session using

set path=%path%;C:\python26

To add this to the path permanently, modify the path variable in the win-dows control panel. For some of the computers listed below we do not haveadministrative permissions, so we must the one session method. You can putthis set path ..., in a batch or script file to avoid too much typing.

5

Page 6: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

2.2 Hints for Installing and Running Python on theWindows 7 Machine at the Trailside Center

First to get a command line prompt, go to the box at the bottom of the startmenu and type in it

cmd.exe

Sometimes ”command prompt” appears in the list of Accessaries, afteryou click ”all programs.” Some times you can find ”command prompt” usingWindows help. On this computer add the directory containing ”python.exe”with the command

set path = %path%; c:\program files\python35-32\

To see if this has been accomplished type path at the command line.Version 3 of Python differs from versions 2. One difference that must be

changed is that the print statement in version 2 has for an example the form:

print " a = ", a

Which may produce an error in version 3, which must have parenthesesaround the things to be printed:

print( " a = ", a)

2.3 Hints for Running Python on a Windows 10 Ma-chine at the Johnson County Maker Space

Python 2.7 occurs on the list of APS. Clicking this opens a Python Shellwhere you can do Python interactively. To use an editor to write a pythonprogram on a file, click Idle. A python shell opens. Choose new in thefile menu. Write your program. Run it by selecting ”run module.” If yourprogram uses command line parameters, you might want to run it from a DOSor Windows command prompt. To get a windows command prompt, scrolldown the list of APS to the bottom, finding Windows Sys. Click to littlearrow to find an icon for the command prompt. Create, for convenience, adirectory from the root directory of c: called py to work in. Type python andyou should see the python command prompt, but you won’t see it, becauseon this machine the python program is in a directory called

6

Page 7: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

c:\python27

and this directory is not in the path. To correct this do the following to addthe python27 directory to the path (This is not permanent):

set path=%path%;c:\python27

2.4 Hints for a Vista Machine Running Windows 7

To get a command line:First get a restored run menu, which is hidden in vista. To get the

run menu: Right click on the task bar at the bottom of the screen. Selectproperties. Select the start menu tab at the top. Select classic start menu.Now you should have a restored run menu. Click start, select run. typecmd.exe in the run box. You should get a command icon, which will bepresent also when you restart the computer.

Another method of getting the command line: Right click on the Desktopscreen. Select new. Select shortcut. Type cmd.exe in the shortcut box.

2.5 Hints for Running Python on a Macintosh OS10

System

Python is already installed. You run it from the command line. To get acommand prompt click GO from the top of the screen, then click utilities,then click terminal. If you have a python program, say myprogam.py,then at the command line type

python myprogram.py

To run interactively just type python. To test it, type a=2, then typeb=a+a, then type b. You should get 4. To end python type quit().

3 Some Differences Between Python 2 and

Python 3

We present commands that are different:

7

Page 8: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

Print Statement differences:

In 2:

print ’ x= ’, x

In 3:

print(’ x=’, x)

Division of Integers Differences:

In 2:

m=27

n=42

# k=m/n produces k=0

In 3:

m=27

n=42

\\ k=m/n produces k = 0.6428571429,

\\use // for integer division, when you want an integer 0 for an answer

3.1 Running Python 3 on the Command Line of theRaspberry Pi

Both version 2 and version 3 of Python are installed on the Raspberry Pi.At the command line type python to start version 2, and type python3 tostart version 3. This may be valid for all Debian versions of Linux.

4 Introduction

Python is an interpreted programming language, which can be used in manyways. One can use it in interactive mode as a calculator for computing

8

Page 9: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

formulas. Python is started at the command line by simply typing ”python.”Python is usually installed on Linux and Unix systems including Mac OS10.For windows it is easily obtained and installed.

Sometimes you may see a trailing suffix ”L” on a large integer.Python natively supports complex numbers, and integers of arbitrary

length. Sometimes you may see a trailing suffix ”L” on a large integer.

4.1 Using Python Interactively

To start python type python. You should get the python command prompt,which is:

>>>

To use built in functions you must import the library module that definesthe functions. In the case of mathematical functions the library module iscalled math. The math module contains several standard functions such assine, cosine, exp, pi and so on. Suppose we want to calculate the value ofsin(π/6. So on the Python input line type:

>>>import math

>>># a pound sign starts a comment

>>>v=math.sin(math.pi/6)

>>>v

>>>print v

You can use the python command line to evaluate simple formulas as youwould do on a calculator. So suppose you wanted to find the the gravitationalforce between two particles located a distance r apart using the gravitationalformula

F = Gm1m2

r2.

Suppose we want to calculate the force between a 62 Kg human namedHillary located at coordinates x1 = 3.14159, y1 = 127.84, z1 = −100.3,and a second human of mass 100 named Donald located at coordinatesx2 = 2.718281828459045, y2 = 26.9, z2 = 100.9 in meters. The gravitationalconstant is G = 6.67(1011)(nt)(m2)/Kg2

earth and the earth. We want the force in Newtons.We type

9

Page 10: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

>>>import math

>>>G=6.67E-11

>>>x1=3.14159

>>>y1=127.84

>>>z1=100.3

>>>x2=2.718281828459045

>>>y2=26.9

>>>z2=-100.9

>>>m1=62.

>>>m2=100.

>>>r=math.sqrt((x2-x1)**2 + (y2-y1)**2 + (z2-z1)**2)

>>>print ’r=’, r

>>>F=G*m1*m2/(r**2)

We can do that, but it might be better to put this in a file called force.py,because we can then easily change the values and rerun it.

On the Windows of Linux command line we would type.

python force.py

Here is a copy of the Idle Python shell screen

IDLE 2.6.4

>>> import math

>>> G=6.67E-11

>>> x1=3.14159

>>> x1

3.1415899999999999

>>> y1=127.84

>>> z1=100.3

>>> x2=2.718281828459045

>>> y2=26.9

>>> z2=-100.9

>>> m1=62.

>>> m2=100.

>>> r=math.sqrt((x2-x1)**2 + (y2-y1)**2 + (z2-z1)**2)

>>> print ’r=’, r

10

Page 11: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

r= 225.101094599

>>> F=G*m1*m2/(r**2)

>>> print ’F=’, F

F= 8.16135576383e-12

>>>

4.2 Example

So suppose one wants to compute a point on an ellipse of major axis 10 andminor axis 6 at angle θ = 1.

x = a ∗ cos(θ),

y = b ∗ sin(θ).Point (x, y) are on such an ellipse if the following equation is satisfied.

x2/a2 + y2/b2 = 1.

You could try running the following program in python:

a=5

b=3

theta=1

x =a*cos(theta)

y= b*sin(theta)

print "{", x,y,")"

print x*x/(a*a)+ y*y/(b*b)

But this would produce an error because the mathematical functions re-quire that the math module be imported in order to compute the trigono-metric expressions correctly. But similar commands in a program calledellipsepoint.py will work after importing the math module and adding a”math.” in front of ”cos” and in front of ”sin” also:

import math

a=5

b=3

theta=1

x =a*math.cos(theta)

y= b*math.sin(theta)

print "point=" , "(" , x, "," ,y ,")"

print "x*x/(a*a)+ y*y/(b*b)=", x*x/(a*a)+ y*y/(b*b)

11

Page 12: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

0 1.571 3.142 4.712 6.283x

-1-0

.50

0.5

1y

Figure 1: Function Plotting: The function plotted here is f(x) = cos3(x).It was created with the sequence of programs writefunc.py, a Python programto generate function points, pts2eg.c, a C program to create an eg graphicsfile, pltax.c, a C program to add axes to the plot, and eg2ps.c, a C program toconvert from eg to postscript. These can all be put in a single unix script file,or in a single windows batch file. The final file is beautifully displayed withGhostview, and converted to pdf with Acrobat distiller or with the ps2pdfprogram, which comes with MikTex, or is installed on Linux systems, if TeXis installed. A couple of other useful programs here are pltc.ftn, a FortranProgram to create an eg graphics file, and pltmerge.c, a C program to mergetogether eg files.

12

Page 13: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

So a good place to start learning this language is to read the tutorialsupplied with Python. Python is a free function type interpreter that isavailable for most computers. Python is an extension to operating systemscripting languages like those found on Unix systems. Python can be oper-ated in interactive mode much like a calculator. Some features that makeit useful for scientific calculation are that there is no requirement to declarevariables. Complex numbers are supported. Integers of arbitrary length arealso supported. However, arrays are not part of the language, so computingwith matrices requires an external package be imported. This is available butmay or may not be awkward. Commands can also be stored in script filesand then imported and executed. This prevents the interactive commandsfrom being lost. Mathematical functions such as sine, cosine and so on areavailable in the math package. So if they are to be used one must import themodule:

import maththen to use one of the functions say exp access them like this:math.exp(1)blocks are indicated with indentation rather than with an end statement,

or with a curly bracket as in most languages such as C. So for example inPython

while n < 10 :

print n*n

n= n+1

print " out of while loop"

So the while ends when the indented statements after the while end.Functions are defined with a def statement, like this:

def newtonsmethod(xstart):

x1=xstart

"f(x2) = f(x1) + (x2-x1)*df(x1)=0"

-f(x1)/df(x1) = x2 - x1

x2 = x1 - f(x1)/df(x1)

print x2

x1=x2

When a script is imported, the script is run. Depending on the script,this may change the local environment, so that on reimporting reloading,may not run the same way, (local variables changed and so on). So it maybe required to shut down python (cntrl z on windows, cntrl d on unix.) andstart again.

13

Page 14: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

4.3 Example: Writing Function Points to a File#writefunc.py write the x and y pairs of a function to file outfile.txt

import math

#define function

def f(x):

y=pow(math.cos(x),3)

return y

file1=open(’outfile.txt’,’w’)

n=100

xmn=0.

xmx=2.*math.pi

for i in range(1,n+1):

x=(i-1)*(xmx-xmn)/(n-1) + xmn

y=f( x)

s=repr(x)+" "+repr(y)+"\n"

file1.write(s)

file1.close

4.4 Example: Greatest Common Divisor

The gcd.py program uses command line parameters. These are parametersthat are passed to a program from the command line. For example if yourun the progrm gcd.py with the command

python gcd.py 7142858 999999

then 7142858 and 999999 are the command line parameters and gcd.pycomputes the gcd as

142857

Many programs are written so that if you run the program with no pa-rameters, then you are presented with the help information about what theprogram does and what the parameters are.

The gcd of two integers is the largest integer that divides both of them.

#gcd.py greatest common divisor, getting m and n from the command line

# latest version Aug 28,2017

# May 30, 2014

#see gcdexample, m and n defined in the program

import sys

# python gcd9.py 2010 560

#function greatest common divisor

def gcd(b1,b2):

14

Page 15: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

b=[]

k=[]

rm=[]

v=[]

v=[1,2,3]

b.append(0)

b.append(b1)

b.append(b2)

k.append(0)

rm.append(0)

n=0

while (b2 > 0):

n=n+1

#print " b1= ",b1

#print " b2= ",b2

g=b2

q=b1/b2

k.append(q)

#note, if b2>b1 then q=0, then r=b1 so b1 and b2 are switched

#print " q= ",q

r=b1-b2*q;

b.append(r)

print " ",b1,"=",q,"*",b2,"+",r

rm.append(r)

#print " r= ",r

b1=b2

b2=r

v[0]=g

#print

#print " number of divisions n=",n

#print " b="

#for i in range(1,len(b)):

# print " b[",i,"]=",b[i]

#print " length of k=",len(k)

#print " quotients=",k

#for i in range(1,len(k)):

# print " k[",i,"]=",k[i]

#print " remainders=",rm

#for i in range(1,len(rm)):

# print " rm[",i,"]=",rm[i]

alpha=1

beta=-k[n-1]

#print " g=alpha*b[n-1]+beta*b[n]=",alpha*b[n-1]+beta*b[n]

p=n-2

while (p>0):

tmp=alpha

alpha=beta

beta=tmp-beta*k[p]

#print "p=",p

#print " g=alpha*b[p]+beta*b[p+1]=",alpha*b[p]+beta*b[p+1]

p=p-1

#print

#print " alpha=",alpha," beta=",beta

#print " g=alpha*b[1]+beta*b[2]=",alpha*b[1]+beta*b[2]

v[1]=alpha

15

Page 16: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

v[2]=beta

return v

#function least common multiple

def lcm(m,n):

v=m*n/gcd(m,n)

return v

#main

#print sys.argv

#print sys.argv[0]

na=len(sys.argv)

#print ’number of arguments = ’, na

if( na < 3):

print "gcd.py, greatest common divisor of two integers"

print "Also prints multipliers alpha and beta of m and n"

print "that produce the gcd."

print "as well as m/gcd and n/gcd."

print "Usage: python gcd.py m n "

sys.exit(0)

m=int(sys.argv[1])

print " m= ",m

n=int(sys.argv[2])

print " n= ",n

v=gcd(m,n)

#print " length v = ",len(v)

print " v = [gcd,alpha,beta]=",v

print " gcd(m,n)= ",v[0]

alpha=v[1]

#print " alpha=",alpha

beta=v[2]

#print " beta=",beta

print " alpha*m+beta*n= ",alpha*m+beta*n

print " m/gcd=", m/v[0]

print " n/gcd=", n/v[0]

Running the gcd.py program without parameters generates some helpinformation:

gcd.py, greatest common divisor of two integers

Also prints multipliers alpha and beta of m and n"

that produce the gcd.

as well as m/gcd and n/gcd.

Usage: python gcd.py m n

Now we run with two integers specified:

$ python gcd.py 200560490130 3451796661527379

m= 200560490130

n= 3451796661527379

gcd(m,n)= 9582441

16

Page 17: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

lcm(m,n)= 72246104125768042470

m= m/gcd = 20930

n= n/gcd = 360221019

gcd(m,n) = 1

4.4.1 GCD Algorithm Proof

Here is a gcd.py printout of a simple example for explaining how the algo-rithm works.

m= 1638

n= 660

1638 = 2 * 660 + 318

660 = 2 * 318 + 24

318 = 13 * 24 + 6

24 = 4 * 6 + 0

v = [gcd,alpha,beta]= [6, 27, -67]

gcd(m,n)= 6

alpha*m+beta*n= 6

m/gcd= 273 (3)(7)(13)

n/gcd= 110 = (2)(5)(11)

There are 4 lines in the calculation.(1) The 4th line shows that 6 divides 24. from the right side of the thirdline we see that 6 divides both 24 and 6, so divides 318, continuing in thismanner upward we see that 6 divides both 660 and 1632.(2) On the other hand if we assume that x > 6, and x divides both 1638and 660, we conclude that x divides 318, continuing downward to line 3, weconclude that x divides both 318 and 24, so divides 6. But this is false. So6 is the greatest common divisor.

For any such gcd calculation these method show that we shall arrive atthe greatest common divisor.

Similar tracing of the calculation shows that α and β as defined in thecalculation give

αm+ βn = gcd.

4.5 Adding Rational Numbers

From Maple:

17

Page 18: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

mn:=2*3*5*7*11*13*14*15*200*189*3574;

mn := 851963472360000

> md:=91*93*101*3*7*35789*1000*13*14;

md := 116919233912754000

> mn/md;

10614780

----------

1456719667

> nn:=2*7*11*17*23*71*47*97;

nn := 19490609446

> nd:=87*11*13*17*43*93*77*23;

nd := 1497870186813

> x:=mn/md + nn/nd;

3650496570782

x := ---------------

179836413050151

Here is a python program to add these same rationals:

#sumrats.py sum of two rationals

import sys

#

#function greatest common divisor

def gcd(m,n):

b1=m

b2=n

18

Page 19: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

while (b2 > 0):

v=b2

q=b1/b2

#note, if b2>b1 then q=0, then r=b1 so b1 and b2 are switched

r=b1-b2*q;

b1=b2

b2=r

return v

#function least common multiple

def lcm(m,n):

v=m*n/gcd(m,n)

return v

#program main

mn=2*3*5*7*11*13*14*15*200*189*3574

md=91*93*101*3*7*35789*1000*13*14

nn=2*7*11*17*23*71*47*97

nd=87*11*13*17*43*93*77*23

print ’ sum of rational numbers’

print ’ ’,mn,’/’,md,’+’,nn,’/’,nd

d=lcm(md,nd)

print ’ lcm=d=’,d

n1=mn*(d/md)

n2=nn*(d/nd)

print ’ quotient =’,n1,’/’,d

print ’ +’,n2,’/’,d

n=n1+n2

print ’ quotient =’,n,’/’,d

g=gcd(n,d)

print ’ gcd(n,d) = ’,g

n=n/g

d=d/g

print ’ quotient =’,n,’/’,d

19

Page 20: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

Running the program we have:

$python sumrats.py

Sum of rational numbers

851963472360000 / 116919233912754000 + 19490609446 / 1497870186813

lcm=d= 6897862646930941704018000

quotient = 50263133069507478120000 / 6897862646930941704018000

+ 89756474257316422556000 / 6897862646930941704018000

quotient = 140019607326823900676000 / 6897862646930941704018000

gcd(n,d) = 38356318000

quotient = 3650496570782 / 179836413050151

This agrees with the Maple answer:

> x:=mn/md + nn/nd;

3650496570782

x := ---------------

179836413050151

4.6 Example: Solar Heating, Using Command Line

Arguments

Here is a program to compute the time it takes to heat a gallon of water fromtemperature t1 to temperature t2. The temperature is in centigrade. It isassumed that all solar radiation is absorbed, and no heat is lost. Note thata pound sign # specifies a comment. Indentation specifies a block of code.When a block such as an if block, a for block, and so on is started, indentedlines are part of the block. Brackets are not used to define the block as in C,or ”begin end” pairs as in Pascal, or ”do enddo” as in Fortran.

#solorheating.py, The time to raise a gallon of water from temperature t1 to t2

#with 1 square meter of solar radiation.

import sys

print sys.argv

print sys.argv[0]

n=len(sys.argv)

print ’number of arguments = ’, n

if n < 3 :

20

Page 21: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

#An indented line starts the content of the if statement

print "solarheating.py, The time to raise one gallon of water from t1 centigrade degrees"

print "to t2 degrees, using one square meter of solar radiation, and assuming all"

print "radiation is absorbed and no energy lost."

print "Usage: python solarenergy.py t1 t2 "

sys.exit(0)

t1=float(sys.argv[1])

t2=float(sys.argv[2])

#

#Define function.

def f(t1,t2):

# Time in seconds to raise one gallon of water from t1 C to t2 C

# Cubic inches in a gallon 231

# Cubic centimeters in a cubic inch 2.54^3

# Heat required to raise a cubic centimeter 1 degree = 1 calorie

# Joules in a calorie 4.184

ccg=231*pow(2.54,3) # Cubic centimeters in a gallon

j=ccg*4.184 #Joules needed to raise one gallon 1 degree

sc=1366 # Solar constant watts /m^2

t=j/sc #Time to raise 1 gallon of water 1 degree, with 1 meter^2 of solar radiation

t12 = t*(t2-t1) #Time to raise 1 gallon of water from t1 degrees to t2 degrees

#print t12, " seconds"

return t12

v=f(t1,t2)

print "The time to raise 1 gallon of water from ", t1, " degrees centigrade to "

print t2 , " degrees centigrade,", " with 1 square meter of solar radiation, is "

print v/60, " minutes"

The program obtains the temperatures from command line arguments.When we type on the command line

python solarheating.py 25 55The strings on the command line, namely, solarheating, 25, and 55 are

the command line arguments. They are stored in the argument vector. Theprogram can access these three arguments as sys.argv[0], sys.argv[1], andsys.argv[2]. These are strings. The last two strings are converted to floatingpoint numbers using the built in float function. The function atof can alsobe used.

4.7 Example: Electric Water Heating

This is a variation of the last example, where the heat is specified as electricalpower in watts on the command line, rather than being a fixed amount ofsolar power.

# 4/2/2014 (Modification of solarheating.py)

21

Page 22: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

#waterheating.py, The time to raise a gallon of water from temperature t1 to t2

#with w watts of power.

import sys

print sys.argv

print sys.argv[0]

n=len(sys.argv)

print ’number of arguments = ’, n

if( n < 4):

print "waterheating.py, The time to raise one gallon of water from t1 centigrade degrees"

print "to t2 degrees, using w watts of power, and assuming"

print "that all power is absorbed and none lost."

print "Usage: python waterheating.py t1 t2 w"

sys.exit(0)

t1=float(sys.argv[1])

t2=float(sys.argv[2])

w=float(sys.argv[3])

def f(t1,t2,w):

# The time in seconds to raise one gallon of water from t1 to t2 (Celsius)

# with w watts.

# Cubic inches in a gallon 231

# Cubic centimeters in a cubic inch 2.54^3

# Heat required to raise a cubic centimeter 1 degree = 1 calorie

# Joules in a calorie 4.184

ccg=231*pow(2.54,3) # Cubic centimeters in a gallon

j=ccg*4.184 #Joules needed to raise one gallon 1 degree

sc=1366 # Solar constant watts /m^2

t=j/w #Time to raise 1 gallon of water 1 degree, with w watts

t12 = t*(t2-t1) #Time to raise 1 gallon of water from t1 degrees to t2 degrees

#print t12, " seconds"

return t12

s=f(t1,t2,w) print "The time to raise 1 gallon of water from ",

t1, " degrees centigrade to " print t2 , " degrees centigrade,

with ", w ," watts, is " print s/60, " minutes" print " rate = ",

60/s, " gallons per minute"

Here is an example of running this program:

python waterheating.py 5 50 13000

The time to raise 1 gallon of water from 5.0 degrees centigrade

to 50.0 degrees centigrade, with 13000.0 watts, is

0.913740167553 minutes

rate = 1.09440302124 gallons per minute

4.8 Example: Converting degrees, minutes, secondsto a decimal number, using Command Line Ar-

guments#dms2d.py, Convert degrees minutes seconds to a single decimal number

22

Page 23: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

import sys

n=len(sys.argv)

print ’number of arguments = ’, n

if( n < 2):

print "dms2d.py, Convert degree minutes seconds to a single number."

print "The first number is degrees, the second if present is minutes,"

print "the third number if present is seconds."

print "Usage: python dms2d.py d m s "

sys.exit(0)

d=float(sys.argv[1])

m=0.

s=0.

if (n > 2):

m=float(sys.argv[2])

if (n > 3):

s=float(sys.argv[3])

def f(d,m,s):

# degrees minutes seconds to a single decimal

y=d + m/60.0 + s/3600.0

return y

v=f(d,m,s)

print " Answer= ", v

The program obtains the degrees minutes and seconds from commandline arguments.Example:

python dms2d.py 30. 30. 30.

Gives: Answer 30.5083333333

4.9 Example: Reading points from a file

Program readxy.py gives an example of reading points from a file. Weobtain the file to be read as an argument to the program. So suppose we hadthe following text file:

1. 2.

3. 4.

1. 2.

3. 4.

5. 6.

7. 8.

9. 10.

23

Page 24: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

1. 2.

3. 4.

1. 2.

3. 4.

8.

1 14

7 8 9

5. 6.

7. 8.

9. 10.

This file has pairs of numbers separated by spaces. There are a couple ofexceptions, one line has only one number, and another has no numbers.

We want to read only the pairs. If there is no filename given on thecommand line, then information is given about how the program is to berun. Each line of the file is read in a for loop. So the variable a is a stringcontaining each line as it is read. The pairs are split out using the stringfunction split into a list s. If there are 2 or more items in the list, the first twoare converted from strings into floating point numbers. There will be morelines read than pairs found, because two lines do not contain pairs. Here isthe program:

#readxy.py read point pairs, x y separated by spaces, from a file

import sys

#print sys.argv

#print sys.argv[0]

na=len(sys.argv)

#print ’number of arguments = ’, na

if( na < 2):

print "readxy.py, read point pairs, x y separated by spaces, from a file"

print "Usage: python readxy.py file "

sys.exit(0)

f1=open(sys.argv[1],’r’)

n=0;

lns=0

for a in f1:

lns=lns+1

s=a.split()

k=len(s)

if k>1:

x=float(s[0])

y=float(s[1])

n=n+1

print "x=",x,"y=",y

print n," pairs read"

print lns," lines read"

f1.close

24

Page 25: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

4.10 Strings

A program for reversing a string shows several manipulations of strings. Astring can be defined by assigning a variable s to text, which is delimitedby a pair of either double quotes or single quotes. Two strings can be con-catenated with a plus sign. A string s can be indexed with an integer asin s(5), which is the sixth character of s because indexing starts with zero.The function len gives the number of characters in a string. A charactercan be added or appended to a string in the same way that two strings areconcatenated as in adding a character of string (s), to the string t, as int = t+ s(j). below. A range is a set of integers from a starting integer to anending integer. Thus range(0,n) is the set of n integers {0, 1, 2, 3, ..., n−1}.

Here is a program for reversing a single string:

#revstring.py reverse a string 1-13-18

s=’abcdefghijklmnopqrstuvwxyz’

t=’’

n=len(s)

for i in range(0,n):

j=(n-1)-i

print j,s[j]

t=t+s[j]

print j, s[j]

print t

This program can be extended to read the string entered as a commandline parameter, or to a program that reverses all strings contained in a file.This version also writes a little extra information to help illustrate how itworks.

25

Page 26: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

We run the program by typing

c:\>python revstring.py

Here is the program output:

25 z

24 y

23 x

22 w

21 v

20 u

19 t

18 s

17 r

16 q

15 p

14 o

13 n

12 m

11 l

10 k

9 j

8 i

7 h

6 g

5 f

4 e

3 d

2 c

1 b

0 a

zyxwvutsrqponmlkjihgfedcba

In the next section we look at a listing of program reversefile.py that re-verses each line of a file. This shows how to remove the newline character,which is included in a string when we read a line from a file, each line readas a single character string.

26

Page 27: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

4.10.1 reversefile.py

#reversefile.py read a file, each line as a string 1/20/2018

#data file f.txt

import sys

#print sys.argv

#print sys.argv[0]

#

#function to reverse characters in string

def reverse(s):

result=""

for c in s:

result = c + result

return result

#

na=len(sys.argv)

print ’ number of arguments = ’, na

print ’ command line arguments ’,sys.argv

if( na < 2):

print "reversefile.py, read all file lines"

print "and reverse each string line read"

print "Sample data file: f.txt"

print "Usage: python reversestring.py file "

sys.exit(0)

f1=open(sys.argv[1],’r’)

n=0;

lns=0

for a in f1:

lns=lns+1

# s.strip(None) stips white space from the ends of string s

# including the extra newline read from the string

# prevents an extra blank line between prints

# See Lee python book, page 81, and Appendix C

print reverse(a).strip(None)

#print lns," number of lines read"

f1.close

27

Page 28: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

4.10.2 Using Program reversefile.py

We use the data file f.txt, which contains the Roman alphabet, two famousnumbers, and a famous palindrome.

abcdefghijklmnopqrstuvwxyz

314159265358979

2718281828459045

amanaplanacanalpanama

A man a plan a canal Panama

To run this program on the file f.txt we type

c:\je\py\python reversefile.py f.tex

getting:

number of arguments = 2

command line arguments [’reversefile.py’, ’f.txt’]

zyxwvutsrqponmlkjihgfedcba

979853562951413

5409548281828172

amanaplanacanalpanama

amanaP lanac a nalp a nam A

28

Page 29: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

4.10.3 Functions for Stripping Strings

When you read a file, each line as a string, the newline character is part ofthe string. When you print it back out, because the Python print statementadds its own newline, and so printing two newlines, getting extra blank linebetween the original lines. To fix this problem one may strip such a readstring of whitespace, and whitespace includes the newline character. We canlook at the program reversefile.py to see how this magic may be accom-plished. We may strip unwanted characters from strings using the s.stripfunction.

Our problem is to to strip unwanted characters, such as whitespace, whichincludes spaces, including any end of line characters. This character strippingmay be done by in python by using a set of library functions. They can stripfrom the beginning, end, or middle of a text string. The strip() method canbe used to strip characters from the beginning or ending of a string, lstrip()and rstrip() perform stripping from the left or right side, respectively. Bydefault, these methods strip whitespace, but other characters can be given.For example:

>>> # Whitespace stripping

>>> s = ’ hello world \n’

>>> s.strip()

’hello world’

>>> s.lstrip()

’hello world \n’

>>> s.rstrip()

’ hello world’

>>>

>>> # Character stripping

>>> t = ’-----hello=====’

>>> t.lstrip(’-’)

’hello=====’

>>> t.strip(’-=’)

’hello’

>>>

\end{verbatim

29

Page 30: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

Discussion

The various strip() methods are commonly used when reading and

cleaning up data for

later processing. For example, you can use them to get rid of whitespace,

remove quotations, newline characters and so on..

Be aware that stripping does not apply to any text

in the middle of a string. For example:

\begin{verbatim}

>>> s = ’ hello world \n’

>>> s = s.strip()

>>> s

’hello world’

>>>

If you needed to do something to the inner space, you would need to useanother technique, such as using the replace() method or a regular expressionsubstitution. For example:

>>> s.replace(’ ’, ’’)

’helloworld’

>>> import re

>>> re.sub(’\s+’, ’ ’, s)

’hello world’

>>>

30

Page 31: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

4.10.4 Partitioning Strings

The function s.partition(sep) partitions a string s into three parts returnedas a tuple. If the separator is found the tuple consists in a first part, up tothe separator string, then the separator string, and then the string from theseparator to the end of the string. If the separator is not found then thereturned tuple has a first part the whole string, then followed by two emptystrings.

Here is a program called partition.py displaying three possible results:

# partition.py

string = "Python is fun"

print(string.partition(’is ’))

# So, ’is ’ separator was found,

# and so (’Python ’, ’is ’, ’fun’) is printed.

#

print(string.partition(’not ’))

# So ’not’ separator is not found,

# and so (’Python is fun’, ’’, ’’) is printed.

#

string = "Python is fun, isn’t it"

print(string.partition(’is’))

# So splits at first occurrence of ’is’

# and so (’Python ’, ’is’, " fun, isn’t it") is printed.

31

Page 32: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

4.11 Functions

Functions are defined using the word def as in

def f(x):

return x**2 + 2.*x +1

print f(3.)

4.12 Functions and Scope

Let us look at a function example which reverses a string that has been readby the python input command.

def reversefunction(s):

result = ""

for c in s:

result = c + result

return result

#

t = input("Enter a string: ")

print " reverse of ", t

print " is" , reversefunction(t)

Notice that the string that is input must be enclosed in quotes. This isbecause the Python input function must recognise the type of the input.Also if the string were a line of text, input must not stop at a space, whichit would do if there were no quotes.

4.12.1 The Scope of Variables

Reference: See Python Programming Fundamentals p. 119, by Kent D.Lee. This is a very simple introductory book, but takes a Computer Scienceapproach, and has some interesting insights.

Inside of a function the variables normally have local scope, except forthe function arguments. That is the variables are unknown outside of thefunction.

In most languages there is a method of creating global variables, andPython has this, which is used by designating a variable with the keyword

32

Page 33: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

global, which gives access to this variable in all functions defined in yourprogram.

But there is another kind of scope in python called enclosing scope, whichis not common elsewhere. It is called enclosing scope.

4.13 Integers

There are traditional integers in Python as in most languages, but there arealso long integers, which can be of any length (within memory limits). Nowordinary short integers, that is traditional integers, which used to be 32 bits,will not overflow in Python but rather will be converted to the unlimitedlength integers automatically. Such integers make doing number theory cal-culations in python very possible.

modulo operator The modulo binary operator mod, used as in k mod n,is the remainder of k/n. This is the operator % in Python, so that k mod nis k%n in python. So if k%n = 0, then n divides k.

4.13.1 My Modulo Program mod.py

The greatest integer function, given a real value x, is written [x] andequals the largest integer less than or equal to x. For example [5.3] = 5,and we have the repeating decimal −17.0/7 = −2.42857142857142857...,so [−17.0/7] = −3. Now computer languages return the greatest integerfor division of two integers. Thus you will find in Python, and computerlanguages in general, one hopes, that they return the value -3 for −17/7.

33

Page 34: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

Here is my program mod.py:

# mod.py m mod(n) program using function mod(m,n) 6-3-14

# 2-9-2018 added comparison with built in python mod function

import sys

#+ function m mod n

def mod(m,n):

q=m/n

r=m-q*n

print m,"=",q,"*",n,"+",r

return r

#program main mod

#print sys.argv

#print sys.argv[0]

na=len(sys.argv)

#print ’number of arguments = ’, na

if( na < 3):

print "mod.py, compute: m mod n"

print "Usage: python mod.py m n "

sys.exit(0)

m=int(sys.argv[1])

print " m= ",m

n=int(sys.argv[2])

print " n= ",n

v=mod(m,n)

print m," mod ",n ," = ",v

print " using python function m % n =", m % n

34

Page 35: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

Here are two examples of running the program, computing 17 mod 7, andcomputing -17 mod 7:

c:\je\py\python mod.py 17 7

m= 17

n= 7

17 = 2 * 7 + 3

17 mod 7 = 3

using python function m % n = 3

and

c:\je\py\python mod.py -17 7

m= -17

n= 7

-17 = -3 * 7 + 4

-17 mod 7 = 4

using python function m % n = 4

4.13.2 System Function sys.maxint

In Python, there is a way to get the largest short integer that one can use.Is there some pre-defined constant like

INT_MAX?

No, Python has arbitrary precision integers so there is no true fixed max-imum. The size of integers is only limited by available memory.

In Python 2, there are two types, int and long int, so ints use a type fora short integer like say the C language, while longs are of arbitrary length.You can use sys.maxint to find the maximum int. But ints are automaticallypromoted to long, so you usually don’t need to worry about it:

sys.maxint + 1

works fine and returns a long.sys.maxint does not even exist in Python 3, since int and long were unified

into a single arbitrary precision int type.Python longs can be arbitrarily large. If you need a value that’s greater

than any other value, you can use

35

Page 36: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

float(’inf’).

This is because Python has no trouble comparing numeric values of dif-ferent types.

4.13.3 Program for Prime Numbers from Python Tutorial

This program helps explain the for loop, which differs from tradition in hav-ing an else: at the end, which executes the else: after the loop sequence hasbeen finished. Because of this the break command operates a bit differentlythan in a normal for loop or do loop, such as in C or in Fortran. Thisprogram does a lot of unnecessary printing to help explain what is going on.

# prime.py 1/23/2018

# For a short version of this, see page 21 of the Python 2.6.4

# tutorial.pdf (in c:\scitools\python2.6.4, or in \je\py)

primes=[]

npf=0

for n in range(2, 500): # first for loop

print ’n = ’,n

for x in range(2, n): # second for loop

print ’x=’,x

if n % x == 0: # n % x, is n Mod(x)

print n, ’equals’, x, ’*’, n/x

break

else:

print ’ executing else: of second for loop’

# loop fell through without finding a factor

print n, ’is a prime number’

npf=npf+1

primes.append(n)

else:

print ’ executing else: of first for loop’

print ’ number of primes found’, npf

print ’primes:=’

print primes

print ’left all of the for loops’

36

Page 37: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

4.13.4 Program for Fibonaccii Sequence From Python Tutorial

We can create a function that writes the Fibonacci series to an arbitraryboundary:

See page 21 of the Python 2.6.4

tutorial.pdf (in c:\scitools\python2.6.4)

>>> def fib(n): # write Fibonacci series up to n

... """Print a Fibonacci series up to n."""

... a, b = 0, 1

... while a < n:

... print a,

... a, b = b, a+b

...

>>> # Now call the function we just defined:

... fib(2000)

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

4.14 A List of some Python Commands and Their Use

dir() (lists current functions)

dir(math) (lists functions in module math)

import math

math.sin(x) (the sine function in the module math)

math.int(x) convert to integer

math.round(x) round to integer

math.floor(x) greatest integer in x

float(k) convert to float

import sys

sys.path

#!/usr/bin/env python

(in unix pound bang tells system to use python to execute the script)

a=1.5+0.5j, a.real, a.imag , abs(a) (complex numbers)

hello = "This is a rather long string containing\n\

several lines of text just as you would do in C.\n\

Note that whitespace at the beginning of the line is\

significant."

37

Page 38: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

s = ’supercalifragilisticexpialidocious’

len(s)=34

list: a = [’spam’, ’eggs’, 100, 1234]

b=a.append(3.14)

while b < 10:

print ’The value of i is’, i

a = [’cat’, ’window’, ’defenestrate’], for x in a:

for i in range[2,23]:

def mean(a): .... return m (function definition)

list.append(x)

list.extend(L)

list.insert(i, x)

list.remove(x)

list.reverse()

a=[1, 66.25, 333, 333, 1234.5]

del a[2:4]

t = 12345, 54321, ’hello!’ ( tuple)

file1=open(’outfile.txt’,’w’)

file1.write(s)

file1.close (python)

import sys

print sys.argv[0]

n=len(sys.argv)

sys.exit(0)

t1=float(sys.argv[1])

if( n < 3):

dir() list currently defined names (python)

repr() convert values to strings (python)

f.read() reads entire file

f.readline() reads a line

for line in f:

print line

s="1.23 4.56 7.13"

a=s.split()

x=float(a[0])

y=float(a[1])

z=float(a[2])

38

Page 39: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

for a in file1:

import sys

print sys.argv

print sys.argv[0]

na=len(sys.argv)

print ’number of arguments = ’,na

x=float(s[0])

4.15 Vectors

We may store vectors as lists. Here is a program defining some vector oper-ations:

#vectors.py, sum, difference, norm, products of vectors

#

import math

#+ vsum sum of vectors

def vsum(a,b):

c=[]

n=len(a)

for i in range(0,n):

c.append(0.)

for i in range(0,n):

c[i]=a[i]+b[i]

return c

#+ vdiff difference of vectors

def vdiff(a,b):

c=[]

n=len(a)

for i in range(0,n):

c.append(0.)

for i in range(0,n):

c[i]=a[i]-b[i]

return c

#+ vsm scalar multiple of vector

def vsm(s,a):

c=[]

n=len(a)

for i in range(0,n):

c.append(0.)

for i in range(0,n):

c[i]=s*a[i]

return c

#+ vnorm norm of a vector

def vnorm(a):

n=len(a)

vn=0.

for i in range(0,n):

vn=vn+a[i]*a[i]

vn=math.sqrt(vn)

39

Page 40: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

return vn

#+ crsspr cross product of vectors

def crsspr(a,b):

c=[0.,0.,0.]

c[0]=a[1]*b[2]-a[2]*b[1]

c[1]=a[2]*b[0]-a[0]*b[2]

c[2]=a[0]*b[1]-a[1]*b[0]

return c

#+ dotpr dot product of vectors

def dotpr(a,b):

n=len(a)

s=0.

for i in range(0,n):

s=s+a[i]*b[i]

return s

# main

a=[1.,2.,3.]

print "a=",a

b=[3.,5.,1.]

print "b=",b

s=9.

print "s=",s

aplusb=vsum(a,b)

print "aplusb=",aplusb

aminusb=vdiff(a,b)

print "aminusb=",aminusb

sa=vsm(s,a)

print "sa=",sa

norma=vnorm(a)

print "norma=",norma

axb=crsspr(a,b)

print "axb=",axb

adotb=dotpr(a,b)

print "adotb=",adotb

norma=math.sqrt(dotpr(a,a))

print "norma=",norma

4.16 Formatting Output

In this example we have an example of formatting numbers . This is a methodapplied to strings.

#inductance.py

import sys

import math

f=float(sys.argv[1])

print "f=",f," Hertz"

omega=2.*math.pi*f

C=2.0e-6

print " C=",C*1.e6,"microfarads"

L=1./(omega*omega*C)

40

Page 41: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

print " L=",L*1000.," millihenries"

fmin=500.

fmax=2000.

R=1000.

n=30

for i in range(0,n):

f=i*(fmax-fmin)/(n-1)+fmin

omega=2.*math.pi*f

XL=omega*L

XC=-1/(omega*C)

print ’i=’,i,’f={0:.1f}’.format(f),’XL={0:.4f} XC={1:.4f}’.format(XL,XC)

#print ’XL={0:.5f}’.format(XL)

#

4.17 Creating a Module

Pretty much any Python program containing function definitions is a module.So for example the following program called vec.py can serve as a module forvector operations.

#vec.py, sum, difference, norm, products of vectors

import math

#+ vsum sum of vectors

def vsum(a,b):

c=[]

n=len(a)

for i in range(0,n):

c.append(0.)

for i in range(0,n):

c[i]=a[i]+b[i]

return c

#+ vdiff difference of vectors

def vdiff(a,b):

c=[]

n=len(a)

for i in range(0,n):

c.append(0.)

for i in range(0,n):

c[i]=a[i]-b[i]

return c

#+ vsm scalar multiple of vector

def vsm(s,a):

c=[]

n=len(a)

for i in range(0,n):

c.append(0.)

for i in range(0,n):

c[i]=s*a[i]

return c

#+ vnorm norm of a vector

def vnorm(a):

n=len(a)

41

Page 42: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

vn=0.

for i in range(0,n):

vn=vn+a[i]*a[i]

vn=math.sqrt(vn)

return vn

#+ crsspr cross product of vectors

def crsspr(a,b):

c=[0.,0.,0.]

c[0]=a[1]*b[2]-a[2]*b[1]

c[1]=a[2]*b[0]-a[0]*b[2]

c[2]=a[0]*b[1]-a[1]*b[0]

return c

#+ dotpr dot product of vectors

def dotpr(a,b):

n=len(a)

s=0.

for i in range(0,n):

s=s+a[i]*b[i]

return s

# end

Here is a program that imports vec as a module:

#vectest.py

import vec

# main

a=[1.,2.,3.]

print "a=",a

b=[3.,5.,1.]

print "b=",b

s=9.

print "s=",s

aplusb=vec.vsum(a,b)

print "aplusb=",aplusb

aminusb=vec.vdiff(a,b)

print "aminusb=",aminusb

sa=vec.vsm(s,a)

print "sa=",sa

norma=vec.vnorm(a)

print "norma=",norma

axb=vec.crsspr(a,b)

print "axb=",axb

adotb=vec.dotpr(a,b)

print "adotb=",adotb

norma=math.sqrt(vec.dotpr(a,a))

print "norma=",norma

4.18 Using Eval

The eval function can be used to interpret an expression. Here is an example:

42

Page 43: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

#eval.py

import math

def f(x,s):

y=eval(s)

return y

x=2

s="x**3+math.sin(math.pi/2.)"

w=f(x,s)

print w

So eval interprets expressions. So eval interprets expressions.

4.19 Object Oriented Programming Example

Here is a program defining a class. Here is a program defining a class.

class point:

def __init__(self,x=0,y=0):

self.x=x

self.y=y

def norm(self):

return math.sqrt(self.x**2+self.y**2)

def __eq__(self,other):

return self.x==other.x and self.y==other.y

def __repr__(self):

return "Point({0.x!r}, {0.y!r})".format(self)

def __str__(self):

return "({0.x!r}, {0.y!r})".format(self)

def __add__(self,other):

x=self.x+other.x

y=self.y+other.y

return point(x,y)

a=point()

s=repr(a)

print s

b=point(3,4)

s=repr(b)

print "b=", b

print " b= ",str(b)

print " a is equal to b, is ",a==b

print " a is not equal to b, is",a!=b

c=point("hello","world")

print str(c)

d=point(2,3)

print "d=",str(d)

e=b+d

s=str(e)

print "b+d=",s

43

Page 44: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

4.20 Operations on the Bytes of a File

The following Python program converts any semicolon character in a textfile to a new line. It is used in batch file stemdocspy.bat as a substitutefor the C program semi2nl.c used in program stemdocs.bat and in someUnix and MacOS programs. These programs search stem2 document filesby searching stemdocs.txt, which is stored on the stem2.org website andalso locally. stemdocs.bat uses the techniques originally used in searchingmy notes file (notes.txt). This batch program is called notes.bat, and onUnix systems is called notes.sh. The reason to use this substitute Pythonprogram is because on a later MacOS system I don’t have access to a Ccompiler. This Python code below writes a CR (ascii(13) and LF (ascii 10) ,that is a carriage return and a line feed) for the DOS and windows IBM PC.Some Python documentation says that you can define the newline characteras just a backward ”slash nl” as in C programs, which will adjust itself for theparticular system. However, in tests this does not seem to work correctly.(so this python program needs to be changed slightly for the MacOS andLinux cases, writing only the ascii 10 LF character). See the use of finally:in semi2nl.py

#semi2nl.py replace semicolons with newline 12/29/16

import sys

#print sys.argv

#print sys.argv[0]

na=len(sys.argv)

#print "number of arguments",na

if( na < 3):

print "semi2nl.py, read a text input file, and write each character"

print " to an output file, while converting each semicolon to a newline"

print " Usage: python semi2nl.py infile outfile"

sys.exit(0)

#f1 = open("aa.txt", "rb")

#f2 = open("bb.txt", "wb")

f1=open(sys.argv[1],"rb")

f2=open(sys.argv[2],"wb")

c13=chr(13)

c10=chr(10)

try:

byte = f1.read(1)

# print " byte= ",byte," ",ord(byte)

while str(byte) != "":

# print " byte= ",byte," ",ord(byte)

if(ord(byte) != 59):

f2.write(byte)

else:

# g.write(’\n’)

f2.write(c13)

44

Page 45: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

f2.write(c10)

byte = f1.read(1)

finally:

f1.close()

f2.close()

4.21 A Matrix Class

Here is a Python Class for handling matrices. Matrices are stored as objects.The numbers in the matrix are stored as a list of numbers. Also stored isthe number of rows and columns. We can initialize a matrix in three ways.So to use the matrix class, which is stored in the file mat.py, we must firstimport it.

import mat

We may initialize a matrix in three ways. A matrix b can be defined byproviding a list, the number of rows, and columns

b=mat.matrix([1.,2.,3.,4,4,1],3,2)

This defines the matrix

b =

1 23 44 1

with 3 rows and 2 columns. The list in the matrix object is called ”a”,the row size is called ”m” and the column size is called ”n”. Classes inPython are public, so the numbers in the matrix could be changed directlyby manipulating the list. But better way is to use the get and put functions.

A second way of initializing a matrix is to define it as a string usingsemicolons in a manner similar to matlab, where a semicolon indicates a newrow. So

b=mat.matrix("1. 2.;3. 4;4 1")

gives

b =

1 23 44 1

45

Page 46: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

Notice in the explicit list definition method there are commas, in the stringdefinition there are no commas. Another difference is that in the explicitlist definition method the matrix elements are evaluated, but in the stringdefinition they are not. So for example if a python variable x has value 2,then

b=mat.matrix([1.,x,3.,4,4,1],3,2)

produces

b =

1 23 44 1

whereas

b=mat.matrix("1. x ;3. 4;4 1")

gives

b =

1 x3 44 1

The third method creates a matrix using a tuple defining the number of rowsand columns.

b=mat.matrix((2,2))

produces a 2 by 2 matrix of zeroes,

b =

[

0 00 0

]

Then the elements can be changed using put

b.put(1,1,1)

b.put(2,2,1)

gives

b =

[

1 00 1

]

These statements mean set the element at row 1 column 1 to 1, and setthe element at row 2 and column 2 to 1. Similarly the statement

46

Page 47: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

y=b.get(2,1)

retrieves the element in the second row and first column of matrix b andplaces it in y.

Matrix addition, multiplication, scalar multiplication, transpose, and in-verse are implemented. Operator overloading is done so that we may writematrix multiplication as

c=a+b

c=a*b

For transpose and inverse we write

b=a.transpose()

b=a.inverse()

To print a matrix b we may type

print b

The current version of mat.py may be found in

stem2.org/je/py.zip

Here is the definition of the matrix class in file mat.py:

#mat.py matrix class, 3/27/2010

import math

class matrix:

def __init__(self,md,*args):

""" Initializes a matrix

md - defines the numbers in the matrix.

It can be a number string, a number list, or a tuple defining the

matrix size.

m - is the number of rows

n - is the number of columns.

m,n may be implied or explicitly given.

Example of a string definition:

a=matrix("1. 2. 3.;4. 5. 6.")

a semicolon separates rows, so this is a 2 row by 3 column matrix

with the first row being

1. 2. 3.

m and n are determined by the placement of semicolons.

This initialization converts the string elements separated by

spaces to floating point numbers. So if you want the elements of

the matrix to be say complex numbers, or strings, use the list

definition.

47

Page 48: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

Example of a list definition:

a=matrix([1., 2., 3., 4., 5., 6.,7.,8.],4,2)

The second argument 4, is taken as m, the number of rows,

The third argument 2, is taken as the number of columns.

So this is a 4 row by 2 column matrix,

the first row being

1. 2.

If only one argument is present the matrix is taken to be a

matrix with a single row.

Example of a tuple definition:

a=matrix((50,17))

The items in the tuple are m,n the size of the matrix.

So in this example the matrix is a 50 row by a 17 column

matrix. When a matrix is initialized with a (m,n) tuple, it

is filled with floating point zeroes. Use the put function

to change an element in the matrix.

"""

self.a=[]

if (type(md)==type("")):

nl=len(md)

s=md.split(";")

m=len(s)

self.m=m

for i in range(0,self.m):

r=s[i].split()

n=len(r)

self.n=n

for j in range(0,n):

self.a.append(float(r[j]))

if (type(md)==type([])):

nl=len(md)

largs=len(args)

if largs==2:

self.m=args[0]

self.n=args[1]

else:

self.m=1

self.n=nl

for i in range(0,nl):

self.a.append(md[i])

if (type(md)==type(())):

self.m=md[0]

self.n=md[1]

zero=0.

nl=self.m*self.n

for i in range(0,nl):

self.a.append(zero)

#end init

#++ p create a print string for a matrix

def p(self):

m=self.m

n=self.n

s=""

for i in range(0,m):

for j in range(0,n):

48

Page 49: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

s=s + " " + repr(self.a[i*n + j])

s=s+"\n"

return s

#++ add add two matrices

def __add__(self,other):

m=self.m

n=self.n

s=[]

for i in range(0,m*n):

s.append(self.a[i]+other.a[i])

sum=matrix(s)

sum.m=m

sum.n=n

return sum

#++ mult multiply two matrices

def __mul__(self,other):

m=self.m

p=self.n

n=other.n

s=[]

for i in range(0,m):

for j in range(0,n):

b=0.

for k in range(0,p):

b=b+self.a[i*p +k]*other.a[k*n + j]

s.append(b)

prod=matrix(s)

prod.m=m

prod.n=n

return prod

#++ get return an element of a matrix at i,j

def get(self,i,j):

n=self.n

e=self.a[(i-1)*n + (j-1)]

return e

#++ put put a value in a matrix at i,j

def put(self,i,j,v):

n=self.n

self.a[(i-1)*n + (j-1)]=v

def transpose(self):

m=self.m

n=self.n

t=matrix((n,m))

for i in range(1,m+1):

for j in range(1,n+1):

v=self.get(i,j)

t.put(j,i,v)

return t

#compute the inverse of a matrix

def inverse(self):

m=self.m

n=self.n

#allocate the matrix b for the inverse

det=1.0

b=matrix((n,n))

49

Page 50: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

#make b the n by n identity matrix

for i in range(1,n+1):

v=1.

b.put(i,i,v)

#make a copy so that the original matrix is not changed

a=matrix((n,n))

for i in range(1,n+1):

for j in range(1,n+1):

a.put(i,j,self.get(i,j))

print " initial a="

print a

print "initial b="

print b

#normalize a by dividing each row by the element of largest magnitude in the row.

for i in range(1,n+1):

bigest=a.get(i,1)

for j in range(2,n+1):

ab=a.get(i,j)

# print "ab= ",ab

if (math.fabs(ab) > math.fabs(bigest)):

bigest=ab

# print "i=",i," bigest= ",bigest

det=det*bigest

if(det == 0.):

return b

for j in range(1,n+1):

a.put(i,j,a.get(i,j)/bigest)

# Divide the corresponding row of b by the largest element.

for j in range(1,n+1):

b.put(i,j,b.get(i,j)/bigest)

print "normalized a="

print a

print "normalized b="

print b

#Start of the elimination to put the matrix a into upper triangular form

#At the jth step, we make the elements of the jth column 0

#below the main diagonal. To start we interchange rows if

#necessary to make the element a_jj the largest element in magnitude.

#This element is called the pivot.

#Then we subtract multiples of this row from the lower rows.

j=1

while(j<n):

print "column j=",j

# print "column j=",j,"a(j,j)=",a.get(j,j)

kk=j+1

l=j

for i in range(kk,n+1):

if (math.fabs(a.get(i,j)) > math.fabs(a.get(l,j))):

l=i

# print "l= ",l

if(l != j):

# interchange rows l and j

det=-det

print "interchange rows ",l," and ",j

for k in range(1,n+1):

50

Page 51: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

c=a.get(l,k)

a.put(l,k,a.get(j,k))

a.put(j,k,c)

for k in range(1,n+1):

c=b.get(l,k)

b.put(l,k,b.get(j,k))

b.put(j,k,c)

print " after interchange a="

print a

# divide row j by pivot

c=a.get(j,j)

det=det*c

if(det == 0.):

return b

print " pivot=",c

for k in range(j,n+1):

a.put(j,k,a.get(j,k)/c)

for k in range(j,n+1):

b.put(j,k,b.get(j,k)/c)

print " after dividing by pivot a="

print a

# Add multiple of row j to lower rows

# to eliminate coefficients below the diagonal

jj=j+1

for i in range(jj,n+1):

am=a.get(i,j)

for k in range(1,n+1):

a.put(i,k,a.get(i,k)-am*a.get(j,k))

for k in range(1,n+1):

b.put(i,k,b.get(i,k)-am*b.get(j,k))

print "after eliminating lower column coefficients a="

print a

j=j+1

# end of while and elimination

print "after completed elimination a="

print a

print "after completed elimination b="

print b

am=a.get(n,n)

det=det*am

if(det == 0.):

return b

for k in range(1,n+1):

b.put(n,k,b.get(n,k)/am)

# Back substitute to compute n-i component

# i=1,2,3,...

nn=n-1

for i in range(1,nn+1):

ni=n-i

for j in range(1,n+1):

nj=ni+1

for ki in range(nj,n+1):

b.put(ni,j,b.get(ni,j)-a.get(ni,ki)*b.get(ki,j))

print "after back substitution and replacement b="

print b

51

Page 52: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

print "det= ",det

return b

def __str__(self):

""" Returns the string representation of the matrix.

Example:

>>> Matrix([1,2,3,4], 2, 2)

1 2

3 4

"""

matrix_as_string = ""

for i in range(0, self.m):

for j in range(0, self.n):

matrix_as_string = "%s %-10s" % (matrix_as_string, self.a[i * self.n + j])

matrix_as_string = "%s\n" % matrix_as_string

return matrix_as_string

def __repr__(self):

""" Returns the representation of a matrix.

Example:

>>> x = matrix([1,2,3,4], 2, 2)

>>> x.__repr___

Matrix([1, 2, 3, 4], 2, 2)

"""

return "matrix(%s, %s, %s)" % (self.a, self.m, self.n)

def main():

""" Exercise some matrix functions.

defining a main function in the class allows

one to execute some examples using the code

if __name__ == "__main__":

main()

that is if there is a function called "main" in the class,

call it. In this way we can hide the examples when the class

definition module is imported.

"""

mat1 = matrix([1, 2, 3, 4, 5, 6, 7, 8, 9], 3, 3)

mat2 = mat1

print

print "mat1 as a string:"

print mat1

print

print "mat1 repr is %s" % mat1.__repr__()

print

print "Let mat2 = mat1"

print "mat1 + mat2:"

print mat1 + mat2

s="1. 2. 3.;4. 5. 6.;7. 8. 9."

a=matrix(s)

print "rows=",a.m

print "columns",a.n

print " (printing matrix a directly) a= "

print a

52

Page 53: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

print " (a print string representation of a) a= "

s=a.p()

print s

print "Check what happens if the row numbers are unequal"

s="10. 20. 30.;4. 5. ;7. "

print "String definition= ", s

b=matrix(s)

print "rows=",b.m

print "columns",b.n

print " b= "

s=b.p()

print s

c=matrix("1 2 3 4 5")

print " c="

print c.p()

d=matrix("1 ;2 ;3 ;4 ;5")

print " d="

print d.p()

e=matrix([1001.,1002.,1003.,1004.])

print "e="

print e.p()

e.m=2

e.n=2

print "e="

print e.p()

z=[5,10,15,20]

e.a=z

print "e="

print e.p()

print "Redefine e to be a 2 by 3 matrix, and"

print "fill it with complex numbers."

z=[1.+ 2j,3-1j,15,6-5j,25.8,3.14159]

e.a=z

e.m=2

e.n=3

print "e="

print e.p()

print "(again) e="

print e

print "Define a matrix with 4 rows and 3 columns, "

print "it is filled with zeroes, by default"

f=matrix((4,3))

print " f= "

print f.p()

print "Add matrices"

print " a= "

print a.p()

print "g=a"

g=a

print " g= "

print g.p()

h=g+a

53

Page 54: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

print " h=a+g "

print " h= "

print h.p()

print " h(2,2) = ",h.get(2,2)

print " h(3,2) = ",h.get(3,2)

print " h(1,1) = ",h.get(1,1)

print " Set the element in the 2nd row and 3rd column of h to 27.0"

v=27.

h.put(2,3,v)

print " h= "

print h.p()

aa=matrix("2 3;1 2")

print " aa="

print aa.p()

bb=matrix("3 1;4 2")

print " bb="

print bb.p()

print "cc=aa*bb="

cc=aa*bb

print "cc= "

print cc.p()

print "cc repr is %s" % cc.__repr__()

print "cc= "

print cc

t=matrix(["x","x^2","x^3","x^4"],2,2)

print " t= "

print t

m27=matrix("1 2;3 4;5 6")

print " m27="

print m27

m28=m27.transpose()

print "m28 is the transpose of m27"

print "m28="

print m28

m29=matrix([1. ,2. ,5. , 3. ,2. ,3. ,4., 0., 1.],3,3)

print "m29="

print m29

b=m29.inverse()

print " inv(m29)= "

print b

print "m29*m29.inverse()="

print m29*b

print "Here we can call main() to execute some examples"

if __name__ == "__main__":

main()

Here is the output of the program:

rows= 3

columns 3

(printing matrix a directly) a=

1.0 2.0 3.0

54

Page 55: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

4.0 5.0 6.0

7.0 8.0 9.0

(a print string representation of a) a=

1.0 2.0 3.0

4.0 5.0 6.0

7.0 8.0 9.0

Check what happens if the row numbers are unequal

String definition= 10. 20. 30.;4. 5. ;7.

rows= 3

columns 1

b=

10.0

20.0

30.0

c=

1.0 2.0 3.0 4.0 5.0

d=

1.0

2.0

3.0

4.0

5.0

e=

1001.0 1002.0 1003.0 1004.0

e=

1001.0 1002.0

1003.0 1004.0

e=

5 10

15 20

Redefine e to be a 2 by 3 matrix, and

fill it with complex numbers.

e=

(1+2j) (3-1j) 15

(6-5j) 25.800000000000001 3.1415899999999999

(again) e=

(1+2j) (3-1j) 15

(6-5j) 25.8 3.14159

Define a matrix with 4 rows and 3 columns,

it is filled with zeroes, by default

f=

0.0 0.0 0.0

0.0 0.0 0.0

0.0 0.0 0.0

0.0 0.0 0.0

55

Page 56: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

Add matrices

a=

1.0 2.0 3.0

4.0 5.0 6.0

7.0 8.0 9.0

g=a

g=

1.0 2.0 3.0

4.0 5.0 6.0

7.0 8.0 9.0

h=a+g

h=

2.0 4.0 6.0

8.0 10.0 12.0

14.0 16.0 18.0

h(2,2) = 10.0

h(3,2) = 16.0

h(1,1) = 2.0

Set the element in the 2nd row and 3rd column of h to 27.0

h=

2.0 4.0 6.0

8.0 10.0 27.0

14.0 16.0 18.0

aa=

2.0 3.0

1.0 2.0

bb=

3.0 1.0

4.0 2.0

cc=aa*bb=

cc=

18.0 8.0

11.0 5.0

cc repr is matrix([18.0, 8.0, 11.0, 5.0], 2, 2)

cc=

18.0 8.0

11.0 5.0

t=

x x^2

x^3 x^4

Here we call main()

mat1 as a string:

1 2 3

4 5 6

56

Page 57: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

7 8 9

mat1 repr is matrix([1, 2, 3, 4, 5, 6, 7, 8, 9], 3, 3)

Let mat2 = mat1

mat1 + mat2:

2 4 6

8 10 12

14 16 18

4.22 Functions With a Variable Number of Arguments

Being able to call a function with an unspecified number of arguments is veryuseful, especially for the initializer of a class. Here is an example of usingvariable arguments, and variable keyword arguments:

def var_args(farg, *args):

print "the fixed arg=", farg

n=len(args)

for k in range(0,n):

print "vararg", k,"=",args[k]

def var_kwargs(farg, **kwargs):

print "the fixed arg=", farg

for key in kwargs:

print "kwargs[%s]= %s" % (key, kwargs[key])

print "calling the var_args function"

var_args(1, "two", 3,[1,2,3,4])

print

print "calling the var_kwargs function"

var_kwargs(farg=1, my_string="two", my_number=3, my_list=[9,99,999])

print "Notice that the call order is not necessarily the print order"

Here is the output generated by this program:

calling the var_args function

the fixed arg= 1

vararg 0 = two

vararg 1 = 3

vararg 2 = [1, 2, 3, 4]

calling the var_kwargs function

the fixed arg= 1

kwargs[my_list]= [9, 99, 999]

kwargs[my_number]= 3

kwargs[my_string]= two

Notice that the call order is not necessarily the print order in the case ofkeyed values, kwargs.

57

Page 58: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

4.23 Class Inheritance

4.24 The Module Search Path

When a module named spam is imported, the interpreter searches for a filenamed spam.py in the current directory, and then in the list of directoriesspecified by the environment variable PYTHONPATH. This has the samesyntax as the shell variable PATH, that is, a list of directory names. WhenPYTHONPATH is not set, or when the file is not found there, the searchcontinues in an installation-dependent default path; on Unix, this is usually.:/usr/local/lib/python.

Actually, modules are searched in the list of directories given by thevariable sys.path which is initialized from the directory containing the in-put script (or the current directory), PYTHONPATH and the installation-dependent default. This allows Python programs that know what theyredoing to modify or replace the module search path. Note that because thedirectory containing the script being run is on the search path, it is im-portant that the script not have the same name as a standard module, orPython will attempt to load the script as a module when that module isimported. This will generally be an error. See section Standard Modules formore information.

4.25 Google Python Tutorial

Below is a link to a Google Tutorial on the Python language.

http://code.google.com/edu/languages/google-python-class/

4.26 Computing the Matrix Inverse Using Gaussian

Elimination

A set of linear equations such as

a11x+ a12y + a13z = b1

a21x+ a22y + a33z = b2

a31x+ a32y + a33z = b3

58

Page 59: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

is solved by repeatedly adding a multiples of one equation to a second equa-tion, to eliminate coefficients, to solve for x, y, z. This technique is calledGaussian elimination. The set of equations can be written as a matrix equa-tion

A

xyz

= b

A systematic way of solving this is to eliminate all coefficients below themain diagonal of A, that is to set them to zero. To compute an inverse weneed to find a matrix B

B =

b11 b12 b13b21 b22 b23b31 b32 b33

So that A ∗B is the identity

A ∗B =

1 0 00 1 00 0 1

This is equivalent to solving three sets of equations where the right sidesare equal to the three columns of the identity. But this elimination can bedone all at once. So here is an example:

So suppose we have

A =

1 2 53 2 34 0 1

and

B =

1 0 00 1 00 0 1

To prevent any possible overflow and to control error we normalize all theelements of A and B to be between 0 and 1 in magnitude, so we divide eachrow by the element of largest magnitude c in each row of A. We simultane-ously perform all row operations also on B in all future row operations. So

59

Page 60: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

here we divide each row of B by the c value found in the row of A. Then Abecomes after normalization

A =

0.2 0.4 1.01.0 0.666666666667 1.01.0 0.0 0.25

and B becomes

B =

0.2 0.0 0.00. 0.333333333333 0.00. 0. .25

The next step is to select what is called the pivot in the first column. Weselect a row with a largest magnitude element. In this case the second rowhas an element of magnitude 1 in the first column, so we interchange rows 1and 2 and get

A =

1.0 0.666666666667 1.00.2 0.4 1.01.0 0.0 0.25

The next step is to divide the row by the pivot. In this case the pivot is1, so the row is unchanged.

A =

1.0 0.666666666667 1.00.2 0.4 1.01.0 0.0 0.25

The next step is to eliminate the coefficients below the pivot by addingmultiples of the row to the lower rows. Then A becomes

A =

1.0 0.666666666667 1.00.0 0.266666666667 0.80.0 −0.666666666667 −0.75

Now we work on the second column. We interchange rows 2 and 3 so thatthe largest element becomes the pivot

A =

1.0 0.666666666667 1.00.0 −0.666666666667 −0.750.0 0.266666666667 0.8

60

Page 61: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

Dividing by the pivot we have

A =

1.0 0.666666666667 1.00.0 1.0 1.1250.0 0.266666666667 0.8

Eliminating the coefficient in the third row we have put A in upper tri-angular form

A =

1.0 0.666666666667 1.00.0 1.0 1.1250.0 0.0 0.5

Now we have also been doing the row operations on B, and they give

B =

0.0 0.333333333333 0.00.0 0.5 −0.3750.2 −0.2 0.1

Now we can solve for the third unknown of the third equation of the firstset of linear equations using the first column of B. Then using this value, wesolve for the second unknown using the value of the first, and so on to solvefor all three unknowns. This process is called back substitution. Then werepeat with the second column of B, then with the third, eventually findingthe complete inverse of A. Our Python inverse algorithm returns this inversein matrix B. So we find the inverse

A−1 =

−0.1 0.1 0.2−0.45 0.95 −0.60.4 −0.4 0.2

Here are the diagnostic values printed out by the inverse function of thematrix class mat.py:

initial a=

1.0 2.0 5.0

3.0 2.0 3.0

4.0 0.0 1.0

61

Page 62: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

initial b=

1.0 0.0 0.0

0.0 1.0 0.0

0.0 0.0 1.0

normalized a=

0.2 0.4 1.0

1.0 0.666666666667 1.0

1.0 0.0 0.25

normalized b=

0.2 0.0 0.0

0.0 0.333333333333 0.0

0.0 0.0 0.25

column j= 1

interchange rows 2 and 1

after interchange a=

1.0 0.666666666667 1.0

0.2 0.4 1.0

1.0 0.0 0.25

pivot= 1.0

after dividing by pivot a=

1.0 0.666666666667 1.0

0.2 0.4 1.0

1.0 0.0 0.25

after eliminating lower column coefficients a=

1.0 0.666666666667 1.0

0.0 0.266666666667 0.8

0.0 -0.666666666667 -0.75

column j= 2

interchange rows 3 and 2

after interchange a=

1.0 0.666666666667 1.0

62

Page 63: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

0.0 -0.666666666667 -0.75

0.0 0.266666666667 0.8

pivot= -0.666666666667

after dividing by pivot a=

1.0 0.666666666667 1.0

0.0 1.0 1.125

0.0 0.266666666667 0.8

after eliminating lower column coefficients a=

1.0 0.666666666667 1.0

0.0 1.0 1.125

0.0 0.0 0.5

after completed elimination a=

1.0 0.666666666667 1.0

0.0 1.0 1.125

0.0 0.0 0.5

after completed elimination b=

0.0 0.333333333333 0.0

0.0 0.5 -0.375

0.2 -0.2 0.1

after back substitution and replacement b=

-0.1 0.1 0.2

-0.45 0.95 -0.6

0.4 -0.4 0.2

a*b=

1.0 0.0 0.0

0.0 1.0 -1.11022302463e-16

-1.11022302463e-16 1.11022302463e-16 1.0

63

Page 64: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

4.27 Examples Using Matrices

Here is an example program, matinverse.py, that computes a determinantand an inverse.

#Example of calculating a determinant and an inverse

#matinverse.py

import mat

a=mat.matrix([1. ,2. ,5. , 3. ,2. ,3. ,4., 0., 1.],3,3)

print "a="

print a

d=a.det()

print "determinant=", d

ainv=a.inverse()

print " ainv= "

print ainv

print "a*ainv="

print a*ainv

Here is the output of the program.

a=

1.0 2.0 5.0

3.0 2.0 3.0

4.0 0.0 1.0

determinant= -20.0

ainv=

-0.1 0.1 0.2

-0.45 0.95 -0.6

0.4 -0.4 0.2

a*ainv=

1.0 0.0 0.0

0.0 1.0 -1.11022302463e-16

-1.11022302463e-16 1.11022302463e-16 1.0

64

Page 65: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

The elements of order 10−16 are of course actually zero. So this is theidentity matrix.

4.28 Python Exercises

Exercise 1. Suppose a batter hits a baseball, so that the ball initially makesan angle of 30 degrees with the ground and lands 300 feet from homeplate.Assume no air resistance. What was the initial velocity magnitude when theball left the bat in meters per second, in miles per hour?Solution Let θ = π/6. Then the initial vertical velocity component is

vy = v sin(θ),

where v is the unknown initial velocity. Let t be the time of flight. Then intime t/2 the ball has reached its maximum height and the vertical velocityis

vy − g(t/2) = 0,

where g is the acceleration of gravity. So

t =2v sin(θ)

g.

Now the horizontal distance travelled in meters is

d = 300ft12in

ft

2.54cm

in

m

100cm

The horizontal distance travelled is

d = v cos(θ)t = v cos(θ)2v sin(θ)

g.

or

v =

dg

sin(2θ),

in meters per second.A mile per hour equals 0.44704 meters per second.

65

Page 66: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

# baseball.py

import math

pi=math.pi

theta=pi/6.

print " angle = ",theta*180./pi," degrees"

#theta=theta/10

d=300.*12.*2.54/100.

print " distance =",d," meters"

g=9.81

v=math.sqrt((g*d)/math.sin(2.*theta))

print " velocity = ",v," meters/second"

print " velocity = ",v*3.6," kilometers/hour"

print " velocity = ",v/.44704," miles/hour"

vx=v*math.cos(theta)

t=d/vx

print " time = ",t," seconds"

vy=v*math.sin(theta)

t2=t/2

h=vy*t2-g*pow(t2,2)/2

print " height = ",h," meters"

The output is

angle = 30.0 degrees

distance = 91.44 meters

velocity = 32.1837982069 meters/second

velocity = 115.861673545 kilometers/hour

velocity = 71.9931062251 miles/hour

time = 3.28071337481 seconds

height = 13.1982271537 meters

Exercise 2. If a baseball is dropped from an airplane, what is its terminalvelocity? That is, at what velocity is the force of the air equal to the gravi-tational force on the ball (Yes, the airplane is in the air, not at the airport,and yes I know that the terminal velocity is zero when it hits the ground.)Can you repeat the first exercise when there is air resistance?Solution Hint The drag force is given by

Fd = −1

2ρv2AD,

where ρ is the air density, v is the velocity, A is the area, and D is the dragcoefficient. The terminal velocity occurs where the drag force equals thegravitational force. The drag coefficient for a sphere is approximately .47,but depends on the Reynolds number. The air density is about

ρ = 1.2

66

Page 67: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

kilograms per cubic meter at 20 degrees Centigrade.Let

C =ρAD

2m,

where m is the mass. Then we have

Fd = −mCv2.

Now the gravitational force is −mg, so equating the drag force magnitude tothe gravitational magnitude we have

mg = mCv2.

Sov =

g/C.

Notice that for a sphere of constant density, the terminal velocity is pro-portional to

√r. So an object of small radius has a small terminal velocity.

The diameter of a baseball is approximately 6.9 cm, so the radius is

r =6.9

(2)(100.)= .0345

meters. A baseball mass is about 135 grams,

m = .135

kilograms.Here is the Python calculation:

#terminal velocity

import math

#density of air kg/m^3

rho=1.2

#drag coefficient

d=.47

#radius meters

r=6.9/(2.*100.)

#cross sectional area

a=math.pi*r**2

67

Page 68: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

# mass kgm

m=.135

# acceleration of gravity m/s^2

g=9.81

c=(rho*a*d)/(2.*m)

v=math.sqrt(g/c)

print "Terminal velocity=",v, "meters per second"

print " =",v/0.44704 ,"miles per hour"

The velocity is about 79.2 miles per hour.

What would be the terminal velocity of a ping bong ball?The second part of the problem requires the numerical solution of a dif-

ferential equation, where the force on the ball is the sum of the gravitationalforce and the drag force. This is a nonlinear differential equation and gen-erally requires an approximate numerical solution. Set up the first orderdifferential equation for this problem. Historically, this problem drove theinvention of the computer. The army wanted to compute artillery rangetables.

The differential equation is given by equating the mass times the accel-eration to the forces

md2r

dt2= −gmj−mC

v‖v‖2‖v‖ .

So the x and y component equations are

d2x

dt2= −C

dx

dt

(

dx

dt

)2

+

(

dy

dt

)2

and

d2y

dt2= −g − C

dy

dt

(

dx

dt

)2

+

(

dy

dt

)2

.

To solve the equations numerically, we need to convert them to a first ordersystem. So let

u1 = x

u2 =dx

dt

68

Page 69: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

u3 = y

u4 =dy

dt.

Thendu1

dt=

dx

dt= u2

du2

dt

=d2x

dt2

= −Cdx

dt

(

dx

dt

)2

+

(

dy

dt

)2

= −Cu2

u22 + u2

4

du3

dt=

dy

dt= u4

du4

dt

=d2y

dt2

= −g − Cdy

dt

(

dx

dt

)2

+

(

dy

dt

)2

= −g − Cu4

u22 + u2

4

So we have a system of four first order differential equations.

du1

dt=

dx

dt= u2

du2

dt= −Cu2

u22 + u2

4

du3

dt= u4

du4

dt= −g − Cu4

u22 + u2

4

69

Page 70: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

The initial values are

u1 = 0, u2 = v cos(θ), u3 = 0, u4 = v sin(θ),

where v is the initial velocity magnitude of the baseball. However, we aregiven a boundary problem rather than an initial value problem. That is wedo not know v, we know the initial position of the ball, and the final positionof the ball, namely on the ground 300 feet away. So to solve the problem weassume an initial velocity and calculate the final location. Then we vary theinitial velocity until we find a velocity that takes us to the 300 foot position.This method of finding the solution of a boundary value problem is calledthe shooting method.

Now we can use Python to calculate a numerical solution by using thesimple Euler method. We take a time step ∆t and compute the changes ofui for i = 1, 2, 3, 4 by adding

dui

dt∆t.

The relative error per step is quite large, so extremely small time steps mustbe taken, with resulting possible roundoff error. To reduce the requirednumber of steps we must use a more sophisticated higher order algorithm.Euler’s method though, does illustrate the general method of solving anordinary differential equation numerically.Exercise 3. Given the vertices of a triangleA = (1.5, 3.2), B = (2.6, 9.1), C =(4.9, 15.2). What is the area of the triangle? Use the cross product function.Solution Hint We can consider A,B ,and C to be three dimensional vectorswith zero as the z component. Then the magnitude of the cross product

(B − A)× (C −A)

is ‖B − A‖‖C − A‖ sin(θ) where θ is the angle between the vectors. This isthe magnitude of the z component, because here the x and y components arezero. So the area of the triangle is one half of this. Write a Python functionto compute the cross product, where a vector is represented by a list of thex,y and z components. Then write a python function to compute the areaof a plane triangle using the cross product. Note, this problem can also besolved by calculating the lengths of the sides and using Heron’s Formula (seethe Vector Analysis review). Here is a program:

70

Page 71: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

#areat.py area of a triangle

#

import math

#+ vdiff difference of vectors, a-ba2,a1)

def vdiff(a,b):

c=[]

n=len(a)

for i in range(0,n):

c.append(0.)

for i in range(0,n):

c[i]=a[i]-b[i]

return c

#+ crsspr cross product of vectors

def crsspr(a,b):

c=[0.,0.,0.]

c[0]=a[1]*b[2]-a[2]*b[1]

c[1]=a[2]*b[0]-a[0]*b[2]

c[2]=a[0]*b[1]-a[1]*b[0]

return c

#+ vnorm norm of a vector

def vnorm(a):

n=len(a)

vn=0.

for i in range(0,n):

vn=vn+a[i]*a[i]

vn=math.sqrt(vn)

return vn

#+ areat area of a plane triangle

def areat(v1,v2,v3):

a1=[0.,0.,0.]

a2=[0.,0.,0.]

a3=[0.,0.,0.]

for i in range(0,2):

a1[i]=v1[i]

a2[i]=v2[i]

a3[i]=v3[i]

a2minusa1=vdiff(a2,a1)

a3minusa1=vdiff(a3,a1)

cp=crsspr(a2minusa1,a3minusa1)

area=math.fabs(cp[2])/2.

return area

# main

#v1=[0.,0.]

#v2=[1.,0.]

#v3=[0.,1.]

v1=[1.5, 3.2]

v2=[2.6, 9.1]

v3=[4.9, 15.2]

print "v1=",v1

71

Page 72: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

print "v2=",v2

print "v3=",v3

area=areat(v1,v2,v3)

print "area=",area

#

#length of sides

a=vnorm(vdiff(v2,v1))

print "length of side a",a

b=vnorm(vdiff(v3,v2))

print "length of side b",b

c=vnorm(vdiff(v1,v3))

print "length of side c",c

#half perimeter

s=(a+b+c)/2.

#Heron’s formula for the area

area=math.sqrt((s-a)*(s-b)*(s-c)*s)

print "area=",area

Exercise 4. Let a 1000 ohm resistor be in series with a 1 microfarad ca-pacitor and an inductor of inductance L. Suppose an alternating voltage isapplied to this circuit. If using an oscilloscope and a function generator, wefind that the maximum voltage on the resistor occurs at 5000 Hertz, thenwhat is the value L of the inductance? If the applied voltage is 20 volts, makea plot of current magnitude as the frequency varies from 0 to 10000 Hertz.Modify the program writefunc.py to generate points for the plot. Then useprograms pnts2eg, pltax, eg2ps, and ps2pdf to display the plot. See thesection on plotting a function with utility programs.Solution Hint The impedance for a series circuit is

Z = R + (ωL− 1

ωC)j

Given a constant applied voltage, the maximum voltage drop occurs acrossR when the imaginary term is zero.

#inductance.py

import sys

import math

f=float(sys.argv[1])

print "f=",f," Hertz"

omega=2.*math.pi*f

C=2.0e-6

print " C=",C*1.e6,"microfarads"

L=1./(omega*omega*C)

print " L=",L*1000.," millihenries"

72

Page 73: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

fmin=500.

fmax=2000.

R=1000.

n=30

for i in range(0,n):

f=i*(fmax-fmin)/(n-1)+fmin

omega=2.*math.pi*f

XL=omega*L

XC=-1/(omega*C)

print ’i=’,i,’f={0:.1f}’.format(f),’XL={0:.4f} XC={1:.4f}’.format(XL,XC)

#print ’XL={0:.5f}’.format(XL)

#

4.29 Python References

Python Essential Reference (4th Edition) (Paperback) David M. BeazleyDavid M. Beazley (Author) Visit Amazon’s David M. Beazley Page

5 Introduction2

$PYTHONPATH

>>> import sys

>>> sys.ps1

’>>> ’

>>> sys.ps2

>>> sys.path

’... ’

>>> sys.ps1 = ’C> ’

C> print ’Yuck!’

Yuck!

C>

# sqr.py

a=5.

print " a value = ",a

x_0=2.

count=1

while count < 8 :

73

Page 74: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

print " x_0=", x_0 ," x_0*x_0 = ", x_0*x_0

x_0=(x_0+a/x_0)/2

count=count+1

reload(sqr)

6 Reading and Writing files

7.2 Reading and Writing Filesopen() returns a file object, and is most commonly used withtwo arguments: ”open(filename, mode)”.

>>> f=open(’/tmp/workfile’, ’w’)

>>> print f

<open file ’/tmp/workfile’, mode ’w’ at 80a0960>

7 Random NumbersThe python module random.py can generate various kinds of random num-bers. Here we do this for an integer range of 10 to humongous.

#randomprg.py a program using the Python random number generator module

import random

import time

ng = 0

nn=200

n1=10

n2=100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

while ng < nn:

n = random.randint(n1, n2)

ng=ng+1

print" n=",n

# time.sleep(2)

8 Python System Path

check system path:

74

Page 75: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

import sys

print(sys.path)

Add a directory to the system path:

import sys

sys.path.append(’/custom/path/to/modules’)

. . .

import <your-python-module>

9 Bibliography

[1] Altom Tim, Programming With Python, 1999, Prima Tech, a divisionof Prima Publishing.

[2] Beazley David M., Python Essential Reference, 2009, 4th Edition,(This book covers both version 2, and version 3, of Python).

[3] Beazley David M., Jones Brian K. Python Cookbook, Recipes forMastering Python 3, O’Reilly, May 2013, 3rd Edition, 706 pages. For

someone who wants very detailed information about typical computer science

programing stuff, not programming for science and mathematics. For some-

one who wants to devote their life to the Python language. See contents in a

file located in my txt directory, or at O’Reilly

[4] Emery James D, Scientific Calculating, Programming, and Writ-ing, 2016, /www/stem2.org/je/sciprog.pdf

[5] Lessa Andre, Python Developer’s Handbook, SAMS Publishing, 2001.

[6] Lutz Mark, Programming Python, O’Reilly, 1996.

[7] Mertz David, Text Processing in Python, Addison-Wesley, 2003.

75

Page 76: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

[8] Monk, Simon, Programming the Raspberry Pi : getting startedwith Python, 2013, (Kansas City Kansas Public Library, 794.81)

[9] Summerfield Mark, Programming in Python 3, 2nd edition, 2010,Addison-Wesley.

[10] Van Laningham Ivan, Sams Teach Yourself Python in 24 Hours,SAMS A Division of Macmillan USA, 2000.

[11] Wentk Richard, Raspberry Pi, John Wiley, 2014.

[12] Monk, Simon, Raspberry Pi Cookbook, First Edition 2014. 004.165,2014 KCK. (very good, python)

76

Page 77: Scientific Programming in Python - Stem2 · Scientific Programming in Python James D Emery Last Modified: 2/17/18 Contents 1 Preface 3 2 Installing and Running Python 4 2.1 Hints

10 Index

blocks 13command line interface 4command line parameters 14def 32fibonacci sequence 37finally: 44for loop 24for loop 37formatting numbers 40functions 32gcd algorithm proof 17gcd 14greatest integer function 33input 32installing python 4interactive python 7list of commands 37math module 11matrices 45mod.py 33mod.py 34modulo operator 33number theory calculations 33object oriented programming 43opening file for bytes 44partition string 31prime number program 36prime numbers 36python tutorial 36range 37rational numbers 17reading bytes 44reading points 23removing new line character 26reversefile.py 27

reversing a string 25revstring.py 25running the modulo program 35scope of variables 32semi2nl.py 44strings 25stripping strings 29variable arguments 57vectors 39versions 2 and 3 differences 7while loop 13while loop 14

77