# Numerical Programming in Python

Λογισμικό & κατασκευή λογ/κού

7 Νοε 2013 (πριν από 4 χρόνια και 6 μήνες)

104 εμφανίσεις

NumericalProgramminginPython
PartI:TheBasicFacilities
NickMaclaren
ComputingService
nmm1@cam.ac.uk,ext.34761
February2006
NumericalProgramminginPythonp.1/??
OverviewofCourse
Basicfacilitiesi.e.usingPython
Integers,oating--point,complexetc.
Arithmeticdetailsandexceptionhandling
Whatweneedtoknow,butdon
'
twantto
ApplicationsofPythonfornumerics
Someimportantwaysofusingit
NumericalProgramminginPythonp.2/??
Practicalsetc.
Manyexamplestoseewhathappens
Codeisindirectory
Demos
Thereareafew,simple,realpracticals
NumericalProgramminginPythonp.3/??
BeyondtheCourse
Email
escience--support@ucs
http://www--uxsup.csx.cam.ac.uk/courses/...
.../NumericalPython
http://www.scipy.org/
NumericalProgramminginPythonp.4/??
Let'sStartSimply
Pythonmakesanexcellentdeskcalculator
Non--trivialworkisapaininmost(e.g.
dc
)
Excel
isbetter,butstillcanbepainful
Notaspowerfulas
Matlab
,inthatrespect
Butismuchmorepowerfulinothers
Veryusefulforone--offcalculations
No
``
cliff
''
betweenthemandcomplexprogram
NumericalProgramminginPythonp.5/??
TrivialPractical
Whatdiametercirclehasareaof10cm
2
?
vol.=πr
2

diam.=2
￿
10/π
python
frommathimportpi,sqrt
print2.0
*
sqrt(10.0/pi)
NumericalProgramminginPythonp.6/??
PythonOutput
3.56824823231
NumericalProgramminginPythonp.7/??
Python'sFacilities
Willnowgothroughallofbuilt--innumerics
Ateachstage,willtryoutfacilities

Whatthey
DO
,notjusthowtouse
Pythonisverystandardcomputerlanguage
Mostthingsapplytootherones,too

Keyfactorishowtomapmathematics
Simpleuseisnothard,ifapproachedright
NumericalProgramminginPythonp.8/??
Python'sIntegers
Nolimitonsize,exceptmemory
Deniteerrors(e.g.
123/0
)raiseexceptions
Exceptionscanbetrappedseelater
Very
bigintegers(e.g.>
10
1000
)canbeslow
Multiply,divide,remainder,conversion,etc.

Mostthingsjustworkasyouwouldexpect
NumericalProgramminginPythonp.9/??
IntegerOperations
`
+
'
,
`
--
'
,
`
*
'
,
`
/
'
(usedfor
÷
)ops,asusual
`
/
'

∞
canalsobewritten
`
//
'
x%y
isremainder,samesignas
`
y
'

note!
Built--infunctions:
abs
absolute(positive)value
Typeconversionfunctions
int

long
divmod(x,y)

(x/y,x%y)
pow(x,y)
(or
x
**
y
)⇒
x
y
NumericalProgramminginPythonp.10/??
Examples
x=divmod(+123,--45)
print+123/--45,+123%--45,x
printx[0]
*
--45+x[1]
Thentryothercombinationsofsigns
print100+23,abs(--123),abs(+123)
printpow(2,10),pow(--5,3),pow(5,0)
Willreturntoexceptionhandlinglater
NumericalProgramminginPythonp.11/??
PythonOutput
--3--12(--3,--12)
123
--312(--3,12)
--123
2--33(2,--33)
--123
233(2,33)
123
123123123
NumericalProgramminginPythonp.12/??
FormattedOutput
Formattedoutputbasedon
C
Simplecase:
%d
or
%<width>d
Ifwidthtoosmall,usesminimumnecessary
print
"%d%d
"
%(123,1234567890)
print
"%7d%7d
"
%(123,1234567890)
Manymoreoptions,butcanbeignored
NumericalProgramminginPythonp.13/??
PythonOutput
1231234567890
1231234567890
NumericalProgramminginPythonp.14/??
Logical(Bitwise)Operations
Dubiouslynumeric,sowillglossover
Seedocumentationformoredetails
Treatsnumberasbinary,twoscomplement
Caninput/outputashex.oroctal
Usualselectionoflogicaloperations
Shiftsscalebyapoweroftwo(useful)
a<<b

a
*
2
b
,
a>>b

a/2
b
NumericalProgramminginPythonp.15/??
Python'sFloating-Point(1)
Thetypeiscalled
oat
andisnumeric

DoesmostthingsyoulearntatA--level
Willreturntonumericalpropertieslater
±<digits>.<digits>[<exponent>]
<exponent>
is[
e
|
E
]
±<digits>
Anythingnon--criticalcanbeomitted
1.23
,
--0.00123
,
1.23e5
,
+1e--5
,
123.4E+5
etc.
Avoidunclear
.23
,
123.
,butwillwork
NumericalProgramminginPythonp.16/??
Floating-PointOperations
Includeseverythingyoucandowithintegers
`
/
'
isoating--pointdivision
`
//
'
,
`
%
'
,
divmod
useintegerquotient

Butallresultsremainas
oat
Also
fmod
,
modf
from
math
(seelater)
Mixingintegersandrealsworksasexpected

Resultisalmostalwaysoating--point
pow(<int>,--<int>)

oat
NumericalProgramminginPythonp.17/??
Examples
print+12.3/--3.4,+12.3//--3.4,+12.3%--3.4,\
divmod(+12.3,--3.4)
Othercombinationsofsignsaresimilar
printabs(--123.4),pow(1.2345,10)
print123.0/34,123/34.0,5
*
2.34567+98
x=--3
printpow(5,--3),pow(5,x),pow(5,--x)
Willreturntoexceptionhandlinglater
NumericalProgramminginPythonp.18/??
PythonOutput
--3.61764705882--4.0--1.3
(--4.0,--1.2999...99989)
--3.61764705882--4.01.3(--4.0,1.29...989)
3.617647058823.0--2.1(3.0,--2.100...001)
3.617647058823.02.1(3.0,2.1000...0001)
123.48.22074056463
3.617647058823.61764705882109.72835
0.0080.008125
NumericalProgramminginPythonp.19/??
Floating-PointFormatting(1)
Verylikeintegerformatting,forsamereason
%<width>.<prec>f
isxed--pointform
%<width>.<prec>e
isscienticform
Lotsofvariations,butcanignoremost

Provideaprecisiondefaultispoor
Aprecisionofzeroprintsinintegerform

Can
trust
only
15
sig.gs

Need
18
sig.gstoguaranteereinput
NumericalProgramminginPythonp.20/??
Floating-PointFormatting(2)
Try:
x=100.0/7.0
print
"%.3f%.5e
"
%(x,x)
print
"%10.5f%20.3e
"
%(x,x)
print
"%.0f%.0e
"
%(x,x)
print
"%.30f%.30e
"
%(9.1,9.1)
print
"%.30f
"
%1.0e--15
NumericalProgramminginPythonp.21/??
PythonOutput
14.2861.42857e+01
14.285711.429e+01
141e+01
9.09999999999999644728632119950
9.09999999999999644728632119950e+00
0.000000000000001000000000000000
NumericalProgramminginPythonp.22/??
Floating-PointFormatting(3)
Resultsalmostalwaysroundcorrectly:
x=(1.234567890125,1.23456789012501)
print
"%.20f%.20f
"
%x
printx[0],x[1]
print
"%.11f%.11f
"
%x
Defaultisabitodd,butstillrounds:
printx[0],x[1],x
NumericalProgramminginPythonp.23/??
PythonOutput
1.23456789012499990044
1.23456789012500989244
1.234567890121.23456789013
1.234567890121.23456789013
(1.2345678901249999,1.2345678901250099)
NumericalProgramminginPythonp.24/??
IntegersInReals
Upto>
±10
15
in
oat
areexact
Conversionto
int
or
long
uses
C
'
srule
This
almost
alwaystruncatestowards
zero
Alternatively,
oor
,
ceil
,from
math
Towards
∞
and
+∞
,as
oat
Exceptfor
NaNs
(seelater),fewproblems
`
Reasonable
'
behaviour
OR
raisesexception
NumericalProgramminginPythonp.25/??
Examples
Try:
x=1.0
foriinxrange(1,30):
x=x
*
5.0
print
"%2d:%.0f%.0f%.0f%.0f
"
%\
(i,x,pow(5,i),x--1,x+1)
Nowlookatline23noticeanything?
Thereare
TWO
thingstonotice
NumericalProgramminginPythonp.26/??
Output
1:
55
4
6
2:2
5
2
5
2
4
2
6
3:12
5
12
5
12
4
12
6
4:62
5
62
5
62
4
62
6
...
21:...12
5
...12
5
...12
4
...12
6
22:...62
5
...62
5
...62
4
...62
6
23:...12
4
...12
4
...12
4
...12
4
24:...62
4
...62
4
...62
4
...62
4
NumericalProgramminginPythonp.27/??
The%dDescriptor
Watchoutfor
%d
with
oat
data
Itconvertstoanintegerbeforeformatting

Usenotrecommended,asmightchange
x=12345.6
y=--x
print
"%.0f%.0f
"
%(x,y)
print
"%d%d
"
%(x,y)
NumericalProgramminginPythonp.28/??
PythonOutput
12346--12346
12345--12345
NumericalProgramminginPythonp.29/??
StandardModules
Module
math
includesfunctions,
pi
and
e
sqrt
,
exp
,
log
,
log10
etc.
Normalandinversetrig.andhyperbolic
Plusthosementionedaboveandsomeothers
Callsthe
C
librarydirectlyseelater

Watchoutforexceptionhandling!

Usebuilt--in
pow
,
NOT
from
math
Module
random
includesreasonablegenerators
NumericalProgramminginPythonp.30/??
Examples
Try:
frommathimportsqrt,cos,log,atan,pi,e
printsqrt(10),log(10),cos(4)
printlog(pow(e,3)),cos(pi/4)
print4
*
atan(1.0),atan(1.0e6)
fromrandomimportrandom,gauss
foriinxrange(0,10):
printrandom(),gauss(100.0,20.0)
NumericalProgramminginPythonp.31/??
PythonOutput
3.162277660172.30258509299
--0.653643620864
3.00.707106781187
3.141592653591.57079532679
0.774001216879102.136112561
0.68237930206105.101301637
0.28760594402139.895961878
...
NumericalProgramminginPythonp.32/??
Practical
Calculate
`
e
'
bysummingseries
1+1/1+1/2+1/6+1/24+...+1/(n!)...
Print
e
,
exp(1)
from
math
andyourresult
Theyshouldallbethesame!
NumericalProgramminginPythonp.33/??
SampleCode
frommathimporte,exp
total=0.0
fact=1.0
n=1
whiletotal+fact>total:
total=total+fact
fact=fact/n
n=n+1
printe,exp(1),total
NumericalProgramminginPythonp.34/??
DecimalFloating-Point
Includedinnew
IEEE754R
standard
Unclearwhen(andif!)hardwarewillhaveit
Pythonhasitinthe
decimal
module
NOT
apanaceaorsignicantlyworse
Theexactnessclaimsarepropaganda
Try
π
,
1.0/3.0
,
1.01
25
,scienticcode
Experimentwithitifyouareinterested
Notyetrecommendedforrealwork
NumericalProgramminginPythonp.35/??
ComplexNumbers(1)
Imaginarypartsare
<number>J
(or
`
j
'
)
1.23+4.56j
or
--1.0j

--1j
are
complex
complex(x,y)

x+y
*
1j
evenif
`
y
'
is
complex

Mostthingsjustworkasyouwouldexpect
Assumingthatyouusecomplexnumbers!

Convertto
oat
forformattedI/O
DefaultI/O(e.g.
print1.23+4.56j
)isne
NumericalProgramminginPythonp.36/??
ComplexNumbers(1)
Allthebuilt--insthat
oat
has

divmod
,
`
//
'
and
`
%
'
are
deprecated
Built--in
real
,
imag
attributes
Built--in
conjugate
method
Module
cmath
isanalogueof
math
Itdoesn
'
thave
pow
,butthatisgood
NumericalProgramminginPythonp.37/??
ComplexExamples
fromcmathimportsqrt,cos,exp,pi,e
x=complex(12.3,3.4)
y=5.67+8.9j
printx,y,x+y,x
*
y,x/y,cos(x)
printx
*
x,pow(x,2),sqrt(--1)
printexp(x),pow(e,x)
printx.real,x.imag,x.conjugate()
printpow(abs(x),2),x
*
x.conjugate()
NumericalProgramminginPythonp.38/??
PythonOutput
(12.3+3.4j)(5.67+8.9j)(17.97+12.3j)
(39.481+128.748j)
(0.898006356025--0.809921793409j)
(14.4697704817+3.93935941325j)
(139.73+83.64j)(139.73+83.64j)1j
(--212401.684765--56141.3550562j)
(--212401.684765--56141.3550562j)
12.33.4(12.3--3.4j)
162.85(162.85+0j)
NumericalProgramminginPythonp.39/??
WhereAreWe?
Thebasicsof
all
Pythonbuilt--innumerics

Manypeoplecangoonandwritecode
Providedthatnothinggoeswrong!

But,inreallife,thingsdogowrong
Willnowdescribethearithmeticmodel
Includingbasicsofexceptions

Needtounderstandthistoavoidpitfalls