-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp05_PythonBasics.tex
More file actions
2688 lines (2281 loc) · 91.4 KB
/
App05_PythonBasics.tex
File metadata and controls
2688 lines (2281 loc) · 91.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\chapter{Python Basics}\label{app:coding}
% Note to the reader: In future versions of this book we will exclusively be using Python
% for the programming language of choice. This appendix will eventually be rolled into
% Chapter 1 as ``Introductory'' material that is optional for students with prior
% programming experience.
In this optional Chapter we will walk through some of the basics of using Python3 - the
powerful general-purpose programming language that we'll use throughout this class. I'm
assuming throughout this Chapter that you're familiar with other programming languages
such as R, Java, C, or MATLAB. Hence, I'm assuming that you know the basics about what a
programming langue ``is'' and ``does''. There are a lot of similarities between several
of these languages, and in fact they borrow heavily from each other in syntax, ideas, and
implementation.
\subsubsection*{Why Python?}
We are going to be using Python in this class since
\begin{itemize}
\item Python is free,
\item Python is very widely used,
\item Python is flexible,
\item Python is relatively easy to learn,
\item and Python is quite powerful.
\end{itemize}
It is important to keep in mind that Python is a general purpose language that we will be
using for Scientific Computing. The purpose of Scientific Computing is {\it not} to build
apps, build software, manage databases, or develope user interfaces. Instead, Scientific
Computing is the use of a computer programming language (like Python) along with
mathematics to solve scientific and mathematical problems. For this reason it is
definitely not our purpose to write an all-encompassing guide for how to use Python.
We'll only cover what is necessary for our computing needs. You'll learn more as the
course progresses so use this chapter as a reference just to get going with the language.
There is an overwhelming abundance of information available about Python and the suite of
tools that we will frequently use.
\begin{itemize}
\item Python \href{https://www.python.org/}{https://www.python.org/},
\item NumPy (numerical python) \href{https://www.numpy.org/}{https://www.numpy.org/},
\item SciPy (scientific python) \href{https://www.scipy.org/}{https://www.scipy.org/}, and
\item SymPy (symbolic python)
\href{https://www.sympy.org/en/index.html}{https://www.sympy.org/en/index.html}.
\end{itemize}
These tools together provide all of the computational power that will need. And they're free!
\section{Getting Started}
Every computer is its own unique flower with its own unique requirements. Hence, we will
not spend time here giving you all of the ways that you can install Python and all of the
associated packages necessary for this course. We highly recommend that you start with
the Anaconda downloader
\href{https://www.anaconda.com/distribution/}{https://www.anaconda.com/distribution/}
since it includes the most up-to-date version of Python as well as some of the common
tools for writing Python code.
The environment in which you code is largely up to personal preference
(or perhaps instructor preference). Jupyter Notebooks seem to be a good modern choice for
coding environments. For more information and for installation of Jupyter see
\href{https://jupyter.org/}{https://jupyter.org/}. The beauty of Jupyter Notebooks is
that you can mix your code and your writing together in a nice and seamless way. A
slightly modern touch on Jupyter Notebooks is an interface called a Jupyter Lab. This is
the exact same as a Jupyter Notebook, but it also gives you an interface for selecting
files, changing directories, building new files, and other such basic functions. From now
on, we'll use the terms ``Jupyter Notebook'' and ``Jupyter Lab'' as synonyms.
In the rest of this chapter we will assume that you have a working version of Python along
with (most likely) a working version of Jupyter Notebooks to work in. Throughout this
chapter all code will be highlighted in boxes so you, the reader, can easily tell that it
is supposed to be code. The output of the code may also be in a box. Lastly, the code
and the output have line numbers so the reader can more easily keep track of the commands,
discuss with their peers, and discuss with their instructor. The problems in this
appendix are
meant to get you going with the Python and you should do every one of them. Remember that
this is not a full replacement for a ``how to program in Python'' resource. We have only
included the essential aspects of the Python language in this chapter as they relate to
the mathematical goals of the book. There is definitely more to say about Python and we
don't intend to cover it all here.
\section{Hello, World!}
As is tradition for a new programming language, we should create code that prints the
words ``Hello, world!'' to the screen. The code below does just that.
\bcode
\begin{lstlisting}
print("Hello, world!")
\end{lstlisting}
\boutput
\begin{lstlisting}
Hello, world!
\end{lstlisting}
In a Jupyter Notebook you will write your code in a code block, and when you're ready to
run it you can press Shift+Enter and you'll see your output.
\begin{problem}
In a Jupyter Notebook have Python print \texttt{Hello, world!} to the screen.
\end{problem}
\begin{problem}
Write code to print your name to the screen.
\end{problem}
Python is a general purpose programming language that can be used for all sorts of
programming tasks. In this book we will focus on uses of Python that are more
computational and mathematical in nature. It is expected that you already know a bit a
programming from another math class that required some coding, possibly from an
introductory computer science class, or from some other exposure to coding. If not then
don't fret -- not all hope is lost. A good place to start is to ask your instructor for
additional programming materials.
We also recommend that you now spend a bit of time poking around in Jupyter Notebooks.
Figure out how to
\begin{itemize}
\item save a file
\item load a new iPython Notebook (Jupyter Notebook) file from your computer's hard drive
\item change the working directory for a Jupyter Notebook.
\item write text in a Jupyter Notebook
\item use the keyboard to switch between writing text and writing code.
\end{itemize}
\section{Python Programming Basics}
\subsection{Variables}
Variables in Python can contain letters (lower case or capital), numbers 0-9, and some
special characters such as the underscore. Variable names should start with a letter. Of
course there are a bunch of reserved words (just like in any other language). You should
look up what the reserved words are in Python so you don't accidentally use them.
You can do the typical things with variables. Assignment is with an equal sign (be careful
R users!).
{\bf Warning:} When defining numerical variables you don't always get floating point
numbers like in MATLAB. In MATLAB if you write \texttt{x=1} then automatically \texttt{x}
is saved as 1.0; a floating point decimal number, not an integer. However, in Python if
you assign \texttt{x=1} it is defined as an \underline{integer} (with no decimal digits)
but if you assign \texttt{x=1.0} it is assigned as a floating point number.
\begin{example}[Number Types in Python]
\bcode
\begin{lstlisting}
# assign some variables
x = 7 # integer assignment of the integer 7
y = 7.0 # floating point assignment of the decimal number 7.0
print(x, type(x))
print(y, type(y))
# multiplying by a float will convert an integer to a float
print(1.0*x , type(1.0*x))
\end{lstlisting}
\boutput
\begin{lstlisting}
7 <class 'int'>
7.0 <class 'float'>
7.0 <class 'float'>
\end{lstlisting}
\end{example}
Note that the allowed mathematical operations are:
\begin{itemize}
\item Addition: \verb|+|
\item Subtraction: \verb|-|
\item Multiplication: \verb|*|
\item Division: \verb|/|
\item Integer Division (modular division): \verb|//| and
\item Exponents: \verb|**|
\end{itemize}
That's right, the caret key, \verb|^|, is NOT an exponent in Python (sigh). Instead we
have to get used to \verb|**| for powers.
\begin{example}[Powers in Python]
Keep in mind that the caret key is not an exponent in Python.
\bcode
\begin{lstlisting}
x = 7.0
y = x**2 # square the value in x
print(y)
\end{lstlisting}
\boutput
\begin{lstlisting}
49.0
\end{lstlisting}
\end{example}
\begin{problem}
What happens if you type $7^2$ into Python? What does it give you? Can you figure
out what it is doing?
\end{problem}
\begin{problem}
Write code to define the variables $a,b,$ and $c$ of your own choosing. Then
calculate $a^2$, $b^2$, and $c^2$. When you have all three computed, check to see if
your three values form a Pythagorean Triple so that $a^2 + b^2 = c^2$ and have Python
simply say True or False to verify that you do, or do not, have a Pythagorean Triple
defined. \\
Hint: You will need to use the == Boolean check just like in other
programming languages.
\end{problem}
\subsection{Indexing and Lists}
Lists are a key component to storing data in Python. Lists are exactly what the name
says: lists of things (in our case, usually the entries are floating point numbers).
{\bf Warning to MATLAB users:} Python indexing starts at 0 whereas MATLAB indexing starts
at 1. We just have to keep this in mind.
We can extract a part of a list using the syntax [start:stop] which extracts elements
between index start and stop-1.\\
NOTE: Python stops reading at the second to last index.
Some things to keep in mind with Python lists:
\begin{itemize}
\item Python starts indexing at 0
\item Python stops reading at the second to last index
\item The following blocks of code show this feature in action for several different lists.
\end{itemize}
\begin{example}
Let's look at a few examples of indexing from lists. In this example we will use the list
of numbers 1 through 8.
\begin{itemize}
\item Create the list of numbers 1 through 8 and then print only the element
with index 0.
\bcode
\begin{lstlisting}
MyList = [1,2,3,4,5,6,7,8]
print(MyList[0])
\end{lstlisting}
\boutput
\begin{lstlisting}
1
\end{lstlisting}
\item Print all elements up to, but not including, the third element.
\bcode
\begin{lstlisting}
print(MyList[:2])
\end{lstlisting}
\boutput
\begin{lstlisting}
[1, 2]
\end{lstlisting}
\item Print the last element (this is a handy trick!).
\bcode
\begin{lstlisting}
print(MyList[-1])
\end{lstlisting}
\boutput
\begin{lstlisting}
8
\end{lstlisting}
\item Print the elements indexed 1 through 4. Beware! This is not the first through fifth
element.
\bcode
\begin{lstlisting}
print(MyList[1:5])
\end{lstlisting}
\boutput
\begin{lstlisting}
[2, 3, 4, 5]
\end{lstlisting}
\end{itemize}
\end{example}
\begin{example}
Let's look at another example of indexing in lists. In this one we'll use the
\texttt{range} command to build the initial list of numbers. Read the code carefully
so you know what each line does.
\bcode
\begin{lstlisting}
MySecondList = list(range(4,20)) # range is a handy command for creating a sequence of integers
print(MySecondList) # notice that it didn't create the last element!
print(MySecondList[0]) # print the first element ... the one with index 0
print(MySecondList[-5]) # print the fifth element from the end
print(MySecondList[-1:0:-1]) # print the last element to the one indexed by 1 counting backwards
print(MySecondList[::2]) # print every other element starting at the beginning
\end{lstlisting}
\boutput
\begin{lstlisting}
[4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
4
15
[19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5]
[4, 6, 8, 10, 12, 14, 16, 18]
\end{lstlisting}
\end{example}
In Python, elements in a list do not need to be the same type. You can mix integers,
floats, strings, lists, etc.
\begin{example}[Lists with elements of mixed type]
In this example we see a list of several items that have different data types: float,
integer, string, and complex. Note that the imaginary number $i$ is represented by
$j$ in Python. This is common in many scientific disciplines and is just another
thing that we'll need to get used to in Python.
\bcode
\begin{lstlisting}
MixedList = [1.0, 7, 'Bob', 1-1j]
print(MixedList)
print(type(MixedList[0]))
print(type(MixedList[1]))
print(type(MixedList[2]))
print(type(MixedList[3])) # Notice that we use 1j for the imaginary number "i".
\end{lstlisting}
\boutput
\begin{lstlisting}
[1.0, 7, 'Bob', (1-1j)]
<class 'float'>
<class 'int'>
<class 'str'>
<class 'complex'>
\end{lstlisting}
\end{example}
\begin{problem}
\begin{enumerate}
\item[(a)] Create the list of the first several Fibonacci numbers:\\
$1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89$.
\item[(b)] Print the first four elements of the list.
\item[(c)] Print every third element of the list.
\item[(d)] Print the last element of the list.
\end{enumerate}
\end{problem}
\subsection{List Operations}
Python is awesome about allowing you to do things like appending items to lists, removing
items from lists, and inserting items into lists. Note in all of the examples below that
we are using the code \\\texttt{variable.command}\\ where you put the variable name, a dot,
and the thing that you would like to do to that variable. For example,
\texttt{MyList.append(7)} will append the number 7 to the list \texttt{MyList}. This is a
common programming feature in Python and we'll use it often.
\begin{example}[Appending To Lists]
The \texttt{.append} command can be used to append an element to the end of a list.
\bcode
\begin{lstlisting}
MyList = [0,1,2,3]
print(MyList)
MyList.append('a') # append the string 'a' to the end of the list
print(MyList)
MyList.append('a') # do it again ... just for kicks
print(MyList)
MyList.append(15) # append the number 15 to the end of the list
print(MyList)
\end{lstlisting}
\boutput
\begin{lstlisting}
[0, 1, 2, 3]
[0, 1, 2, 3, 'a']
[0, 1, 2, 3, 'a', 'a']
[0, 1, 2, 3, 'a', 'a', 15]
\end{lstlisting}
\end{example}
\begin{example}[Removing From Lists]
The \texttt{.remove} command can be used to remove an element from a list.
\bcode
\begin{lstlisting}
MyList.remove('a') # remove the first instance of the string `a` from the list
print(MyList)
MyList.remove(3) # now let's remove the 3
print(MyList)
\end{lstlisting}
\boutput
\begin{lstlisting}
[0, 1, 2, 3, 'a', 15]
[0, 1, 2, 'a', 15]
\end{lstlisting}
\end{example}
\begin{example}[Inserting Into Lists]
The \texttt{.insert} command can be used to insert an element at a location in a list.
\bcode
\begin{lstlisting}
MyList.insert(0,'A') # insert the letter `A` at the 0-indexed spot
MyList.insert(3,'B') # insert the letter `B` at the spot with index 3
# remember that index 3 means the fourth spot in the list
print(MyList)
\end{lstlisting}
\boutput
\begin{lstlisting}
['A', 0, 1, 'B', 2, 'a', 15]
\end{lstlisting}
\end{example}
\begin{problem}
\begin{enumerate}
\item[(a)] Create the list of the first several Lucas Numbers: \\
$1,3,4,7,11,18,29,47.$
\item[(b)] Add the next three Lucas Numbers to the end of the list.
\item[(c)] Remove the number 3 from the list.
\item[(d)] Insert the 3 back into the list in the correct spot.
\item[(e)] Print the list in reverse order (how do you suppose you should do this?)
\item[(f)] Do a few other list operations to this list and report your findings.
\end{enumerate}
\end{problem}
\subsection{Tuples}
In Python, a "tuple" is like an ordered pair (or order triple, or order quadruple, ...) in
mathematics. We will occasionally see tuples in our work in numerical analysis so for now
let's just give a couple of code snippets showing how to store and read them.
\begin{example}[Defining Tuples]
We can define the tuple of numbers $(10,20)$ in Python as follows.
\bcode
\begin{lstlisting}
point = 10, 20 # notice that I don't need the parenthesis
print(point, type(point))
\end{lstlisting}
\boutput
\begin{lstlisting}
(10, 20) <class 'tuple'>
\end{lstlisting}
We can also define the type with parenthesis if we like. Python doesn't care.
\bcode
\begin{lstlisting}
point = (10, 20) # now we define the tuple with parenthesis
print(point, type(point))
\end{lstlisting}
\boutput
\begin{lstlisting}
(10, 20) <class 'tuple'>
\end{lstlisting}
\end{example}
\begin{example}[Unpacking Tuples]
The cool thing is that we can then unpack the tuple into components if we wish.
\bcode
\begin{lstlisting}
x, y = point
print("x = ", x)
print("y = ", y)
\end{lstlisting}
\boutput
\begin{lstlisting}
x = 10
y = 20
\end{lstlisting}
\end{example}
\subsection{Control Flow: Loops and If Statements}
Just like in other programming languages we can do loops and conditional statements in
very easy ways. The thing to keep in mind is that Python is very white-space-dependent.
This means that your indentations need to be correct in order for a loop to work. You
could get away with sloppy indention in other languages (like MATLAB) but not so in
Python. Also, in some languages (like R and Java) you need to wrap your loops in curly
braces. Again, not so in Python.
{\bf Caution:} Be really careful of the white space in your code when you write loops.
\subsubsection{For Loops}
A for loop is designed to do a task a certain number of times and then stop. This is a
great tool for automating repetitive tasks, but it also nice numerically for building
sequences, summing series, or just checking lots of examples. The following are several
examples of Python for loops. Take careful note of the syntax for a for loop as it is the
same as for other loops and conditional statements:
\begin{itemize}
\item a control statement,
\item a colon, a new line,
\item indent four spaces,
\item some programming statements
\end{itemize}
When you are done with the loop just back out of the indention. There is no need for an
``end'' command or a curly brace. All of the control statements in Python are
white-space-dependent.
\begin{example}
Print the first 6 perfect square.
\bcode
\begin{lstlisting}
for x in [1,2,3,4,5,6]:
print(x**2)
\end{lstlisting}
\boutput
\begin{lstlisting}
1.0
4.0
9.0
16.0
25.0
36.0
\end{lstlisting}
\end{example}
\begin{example}
Print the names in a list.
\bcode
\begin{lstlisting}
NamesList = ['Alice','Billy','Charlie','Dom','Enrique','Francisco']
for name in NamesList:
print(name)
\end{lstlisting}
\boutput
\begin{lstlisting}
Alice
Billy
Charlie
Dom
Enrique
Francisco
\end{lstlisting}
\end{example}
You can use a more compact notation sometimes. This takes a bit of getting used to, but is
super slick!
\begin{example}
Create a list of the perfect squares from 1 to 9.
\bcode
\begin{lstlisting}
# create a list of the perfect squares from 1 to 9
CoolList = [x**2 for x in range(1,10)]
print(CoolList)
# Then print the sum of this list
print("The sum of the first 9 perfect squares is",sum(CoolList))
\end{lstlisting}
\boutput
\begin{lstlisting}
[1, 4, 9, 16, 25, 36, 49, 64, 81]
The sum of the first 9 perfect squares is 285
\end{lstlisting}
\end{example}
For loops can also be used to build recursive sequences as can be seen in the next couple
of examples.
\begin{example}
In the following code we write a for loop that outputs a list of the first 10
iterations of the sequence $x_{n+1}=-0.5x_n+1$ starting with $x_0=3$. Notice that
we're using the command \texttt{x.append} instead of $x[n+1]$ to append the new term to the list.
This allows us to grow the length of the list dynamically as the loop progresses.
\bcode
\begin{lstlisting}
x=[3.0]
for n in range(0,9):
x.append(-0.5*x[n] + 1)
print(x)
\end{lstlisting}
\boutput
\begin{lstlisting}
[3.0, -0.5, 1.25, 0.375, 0.8125, 0.59375, 0.703125, 0.6484375,
0.67578125, 0.662109375]
\end{lstlisting}
\end{example}
As an alternative to the code immediately above we can pre-allocate the memory in an array
of zeros. This is done with the clever code \texttt{x = [0] * 10}. Literally multiplying a
list by some number, like 10, says to repeat that list 10 times.
\begin{example}
Now we'll build the sequence with pre-allocated memory.
\bcode
\begin{lstlisting}
x = [0] * 10
x[0] = 3.0
for n in range(0,9):
x[n+1] = -0.5*x[n]+1
print(x) # This print statement shows x at each iteration
\end{lstlisting}
\boutput
\begin{lstlisting}
[3.0, -0.5, 0, 0, 0, 0, 0, 0, 0, 0]
[3.0, -0.5, 1.25, 0, 0, 0, 0, 0, 0, 0]
[3.0, -0.5, 1.25, 0.375, 0, 0, 0, 0, 0, 0]
[3.0, -0.5, 1.25, 0.375, 0.8125, 0, 0, 0, 0, 0]
[3.0, -0.5, 1.25, 0.375, 0.8125, 0.59375, 0, 0, 0, 0]
[3.0, -0.5, 1.25, 0.375, 0.8125, 0.59375, 0.703125, 0, 0, 0]
[3.0, -0.5, 1.25, 0.375, 0.8125, 0.59375, 0.703125, 0.6484375, 0, 0]
[3.0, -0.5, 1.25, 0.375, 0.8125, 0.59375, 0.703125, 0.6484375, 0.67578125, 0]
[3.0, -0.5, 1.25, 0.375, 0.8125, 0.59375, 0.703125, 0.6484375, 0.67578125, 0.662109375]
\end{lstlisting}
\end{example}
\begin{problem}
We want to sum the first 100 perfect cubes. Let's do this in two ways.
\begin{enumerate}
\item Start off a variable called Total at 0 and write a for loop that adds the
next perfect cube to the running total.
\item Write a for loop that builds the sequence of the first 100 perfect cubes.
After the list has been built find the sum with the sum command.
\end{enumerate}
The answer is: 25,502,500 so check your work.
\end{problem}
\begin{problem}
Write a for loop that builds the first 20 terms of the sequence $x_{n+1}=1-x^2$ with
$x_0=0.1$ Pre-allocate enough memory in your list and then fill it with the terms of
the sequence. Only print the list after all of the computations have been completed.
\end{problem}
\subsubsection{While Loops}
A while loop repeats some task (or sequence of tasks) until a logical condition is met.
The structure in Python is the same as with for loops.
\begin{example}
Print the numbers 0 through 4 and then the word ``done''. We'll do this by starting a
counter variable, \texttt{i}, at 0 and incrementing it every time we pass through the
loop.
\bcode
\begin{lstlisting}
i = 0
while i < 5:
print(i)
i += 1 # increment the counter
print("done")
\end{lstlisting}
\boutput
\begin{lstlisting}
0
1
2
3
4
done
\end{lstlisting}
\end{example}
\begin{example}
Now let's use a while loop to build the sequence of Fibonacci numbers and stop when
the newest number in the sequence is greater than 1000. Notice that we want to keep
looping until the condition that the last term is greater than 1000 -- this is the
perfect task for a while loop, instead of a for loop, since we don't know how many steps
it will take before we start the task
\bcode
\begin{lstlisting}
Fib = [1,1]
while Fib[-1] <= 1000:
Fib.append(Fib[-1] + Fib[-2])
Fib
\end{lstlisting}
\boutput
\begin{lstlisting}
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597]
\end{lstlisting}
\end{example}
\begin{problem}
Write a while loop that sums the terms in the Fibonacci sequence until the sum is
larger than 1000
\end{problem}
\subsubsection{If Statements}
Conditional (if) statements allow you to run a piece of code only under certain
conditions. This is handy when you have different tasks to perform under different
conditions.
\begin{example}
\bcode
\begin{lstlisting}
Name = "Alice"
if Name == "Alice":
print("Hello, Alice. Isn't it a lovely day to learn Python?")
else:
print("You're not Alice. Where is Alice?")
\end{lstlisting}
\boutput
\begin{lstlisting}
Hello, Alice. Isn't it a lovely day to learn Python?
\end{lstlisting}
\bcode
\begin{lstlisting}
Name = "Billy"
if Name == "Alice":
print("Hello, Alice. Isn't it a lovely day to learn Python?")
else:
print("You're not Alice. Where is Alice?")
\end{lstlisting}
\boutput
\begin{lstlisting}
You're not Alice. Where is Alice?
\end{lstlisting}
\end{example}
\begin{example}
For another example, if we get a random number between 0 and 1 we could have Python
print a different message depending on whether it was above or below 0.5. Run the code
below several times and you'll see different results each time.
Note: We had to import the \texttt{numpy} package to get the random number generator
in Python. Don't worry about that for now. We'll talk about packages in a moment.
\bcode
\begin{lstlisting}
import numpy as np
x = np.random.rand(1,1) # get a random 1x1 matrix using numpy
x = x[0,0] # pull the entry from the first row, first column of the random matrix
if x < 0.5:
print(x," is less than a half")
else:
print(x, "is NOT less than a half")
\end{lstlisting}
\boutput
\begin{lstlisting}
0.654697487883 is NOT less than a half
\end{lstlisting}
(Take note that the output will change every time you run it)
\end{example}
In many programming tasks it is handy to have several different choices between tasks
instead of just two choices as in the previous examples. This is a job for the
\texttt{elif} command.
\begin{example}
This is the same code as last time except we will make the decision at 0.33 and 0.67
\bcode
\begin{lstlisting}
import numpy as np
x = np.random.rand(1,1) # get a random 1x1 matrix using numpy
x = x[0,0] # pull the entry from the first row, first column of the random matrix
if x < 0.33:
print(x," is less than one third")
elif x < 0.67:
print(x, "is less than two thirds but greater than or equal to one third")
else:
print(x, "is greater than or equal to two thirds")
\end{lstlisting}
\boutput
\begin{lstlisting}
0.654697487883 is less than two thirds but greater than or equal to one third
\end{lstlisting}
(Take note that the output will change every time you run it)
\end{example}
\begin{problem}
Write code to give the Collatz Sequence
$$x_{n+1} = \left\{ \begin{array}{ll} x_n / 2, & \text{$x_n$ is even} \\ 3 x_n + 1, & \text{otherwise} \end{array} \right.$$
starting with a positive integer of your choosing. The sequence will converge to 1 so your code should stop when the sequence reaches 1.
\end{problem}
\subsection{Functions}
Mathematicians and programmers talk about functions in very similar ways, but they aren't
exactly the same. When we say ``function'' in a programming sense we are talking about a
chunk of code that you can pass parameters and expect an output of some sort. This is not
unlike the mathematician's version, but unlike a mathematical function we can have
multiple outputs for a programmatic function. We are not going to be talking about
symbolic computation on functions in this section. Symbolic computations will have to
wait for the `sympy` tutorial.
In Python, to define a function we start with \texttt{def}, followed by the function's
name, any input variables in parenthesis, and a colon. The indented code after the colon
is what defines the actions of the function.
\begin{example}
The following code defines the polynomial $f(x) = x^3 + 3x^2 + 3x + 1$ and then evaluates
the function at a point $x=2.3$.
\bcode
\begin{lstlisting}
def f(x):
return(x**3 + 3*x**2 + 3*x + 1)
f(2.3)
\end{lstlisting}
\boutput
\begin{lstlisting}
35.937
\end{lstlisting}
\end{example}
Take careful note of several things in the previous example:
\begin{itemize}
\item To define the function we can not just type it like we would see it one paper.
This is not how Python recognizes functions. We just have to get used to it.
Other scientific programming languages will allow you to define mathematical
functions in this way, but Python will not.
\item Once we have the function defined we can call upon it just like we would on
paper.
\item We cannot pass symbols into this type of function. See the section on
\texttt{sympy} in this chapter if you want to do symbolic computation.
\end{itemize}
\begin{problem}\label{prob_python:prime_gen}
Define the function $g(n) = n^2 + n + 41$ as a Python function. Write a loop that
gives the output for this function for integers from $n=0$ to $n=39$. It is curious
to note that each of these outputs is a prime number (check this on your own). Will
the function produce a prime for $n=40$? For $n=41$?
\end{problem}
One cool thing that you can do with Python functions is call them recursively. That is,
you can call the same function from within the function itself. This turns out to be
really handy in several mathematical situations.
\begin{example}
Now let's define a function for the factorial. This function is naturally going to be
recursive in the sense that it calls on itself!
\bcode
\begin{lstlisting}
def Fact(n):
if n==0:
return(1)
else:
return( n*Fact(n-1) ) # we are calling the same function recursively.
\end{lstlisting}
When you run this code there will be no output. You have just defined the function so you
can use it later. So let's use it to make a list of the first several factorials. Note
the use of a for loop in the following code.
\bcode
\begin{lstlisting}
FactList = [Fact(n) for n in range(0,10)]
FactList
\end{lstlisting}
\boutput
\begin{lstlisting}
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
\end{lstlisting}
\end{example}
\begin{example}
For this next example let's define the sequence
$$x_{n+1} = \left\{ \begin{array}{ll} 2x_n, & x_n \in [0,0.5] \\ 2x_n - 1, & x_n \in (0.5,1] \end{array} \right.$$
as a function and then build a loop to find the first several iterates of the sequence starting at any real number between 0 and 1.
\bcode
\begin{lstlisting}
# Define the function
def MySeq(xn):
if xn <= 0.5:
return(2*xn)
else:
return(2*xn-1)
# Now build a sequence with this function
x = [0.125] # arbitrary starting point
for n in range(0,5): # Let's only build the first 5 terms
x.append(MySeq(x[-1]))
print(x)
\end{lstlisting}
\boutput
\begin{lstlisting}
[0.125, 0.25, 0.5, 1.0, 1.0, 1.0]
\end{lstlisting}
\end{example}
\begin{example}
Here is another cool example.
A fun way to approximate the square root of two is to start with any positive real number
and iterate over the sequence
$$x_{n+1} = \frac{1}{2} x_n + \frac{1}{x_n}$$
until we are
within any tolerance we like of the square root of two. Write code that defines the
sequence as a function and then iterates in a while loop until we are within $10^{-8}$ of
the square root of 2.
Hint: Import the \texttt{math} package so that you get the square root. More about
packages in the next section.
\bcode
\begin{lstlisting}
from math import sqrt
def f(x):
return(0.5*x + 1/x)
x = 1.1 # arbitrary starting point
print("approximation \t\t exact \t\t abs error")
while abs(x-sqrt(2)) > 10**(-8):
x = f(x)
print(x, sqrt(2), abs(x - sqrt(2)))
\end{lstlisting}
\boutput
\begin{lstlisting}
approximation exact abs error
1.459090909090909 1.4142135623730951 0.04487734671781385
1.414903709997168 1.4142135623730951 0.0006901476240728233
1.4142137306897584 1.4142135623730951 1.6831666327377093e-07
1.4142135623731051 1.4142135623730951 9.992007221626409e-15
\end{lstlisting}
\end{example}
\begin{problem}\label{prob_python:babylonian_sqrt}
The previous example is a special case of the Babylonian Algorithm for calculating square roots. If you want the square root of $S$ then iterate the sequence
$$x_{n+1} = \frac{1}{2} \left( x_n + \frac{S}{x_n} \right)$$
until you are within an appropriate tolerance.
Modify the code given in the previous example to give a list of approximations of the square roots of the natural numbers 2 through 20, each to within $10^{-8}$. This problem will require that you build a function, write a `for` loop (for the integers 2-20), and write a `while` loop inside your `for` loop to do the iterations.
\end{problem}
\subsection{Lambda Functions}
Using \texttt{def} to define a function as in the previous subsection is really nice when
you have a function that is complicated or requires some bit of code to evaluate.
However, in the case of mathematical functions we have a convenient alternative: Lambda
Functions.
The basic idea of a Lambda Function is that we just want to state what the variable is and
what the rule is for evaluating the function. This is the most like the way that we write
mathematical functions. For example, let's define the mathematical function $f(x) = \sin(x^2)+3$ in two
different ways.
\begin{itemize}
\item As a Python function with \texttt{def}:
\begin{lstlisting}
def f(x):
return(np.sin(x**2)+3)
\end{lstlisting}
\item As a Lambda Function:
\begin{lstlisting}
f = lambda x: np.sin(x**2)+3
\end{lstlisting}
\end{itemize}
You can see that in the Lambda Function we are explicitly stating the name of the variable
immediately after the word \texttt{lambda}, then we put a colon, and then the function
definition.
Now if we want to evaluate the function at a point, say $x=1.5$, then we can write code
just like we would mathematically: $f(1.5)$
\begin{lstlisting}
f(1.5) # evaluate the function at x=1.5
\end{lstlisting}
where the result is exactly the floating point number we were interested in:
$f(1.5 \approx 3.778073196887921$.
The distinct mathematical advantange for using Lambda Functions is that the code for
setting up a Lambda Function is about as close as we're going to get to a mathematically
defined function, but the code for evaluating a Lambda Function is {\it exactly} what we
would write mathematically. Additionally, there is less coding overhead than for defining
function with the \mcode{def} command.
We can also define Lambda Functions of several variables. For example, if we want to
define the mathematical function $f(x,y) = x^2 + y\cos(xy)$ we could write the code
\begin{lstlisting}
f = lambda x, y: x**2 + y * np.cos(x*y)
\end{lstlisting}
If we wanted the value $f(2,\pi)$ we could now write the code
\bcode
\begin{lstlisting}
f(2,np.pi)
\end{lstlisting}
\boutput
\begin{lstlisting}
7.141592653589793
\end{lstlisting}
\begin{example}
You may recall Euler's Method from your differential equations training. Euler's
Method will give a list of approximate values of the solution to a first order
differential equation at given times.
Consider the differential equation $y' = -0.25y + 2$ with the initial condition $y(0)
= 1.1$. We can define the right-hand side of the differential equation as a Lambda
Function in our code so that we can call on it over and over again in our Euler's
Method solution. We'll take 10 Euler steps starting at the proper initial condition.
Pay particular attention to how we use the Lambda Function.
\bcode
\begin{lstlisting}
RightSide = lambda y: -0.25*y + 2 # define the right-hand side
dt = 0.125 # define the delta t in Euler's method
t = [0] # initial time
y = [1.1] # initial condition
for n in range(0,10):
t.append(t[n] + dt) # increment the time
y.append(y[n] + dt*RightSide(y[n])) # find approx soln at next pt
print(t) # print the times
print(np.round(y,4)) # round the approx y values to 4 decimal places