54

Learning Mathematics using Python Programming Language2.14 Object Oriented Programming in Python . . . . . . . . . . . . . 21 ... tems the entire le system is inside a directory represented

  • Upload
    others

  • View
    37

  • Download
    0

Embed Size (px)

Citation preview

  • Learning Mathematics

    using

    Python Programming Language

    Ajith Kumar B.P.

    Inter University Accelerator Centre

    New Delhi 110067

    www.iuac.res.in

  • 2

    Preface�Mathematics, rightly viewed, possesses not only truth, but supreme beauty

    � a beauty cold and austere, like that of sculpture, without appeal to any partof our weaker nature, without the gorgeous trappings of painting or music, yetsublimely pure, and capable of a stern perfection such as only the greatest artcan show�, wrote Bertrand Russell about the beauty of mathematics. However,it looks like only the great ones like Russel or Ramanujan are given the capabilityto experience the beauty of mathematics at such higher levels. Still for the lesserones we have fractals, beautiful curves and nice geometrical �gures generatedby seemingly dull equations. This is what we try to explore using a simple toollike the Python programming language. The plot on the cover page is generatedby 8 lines of Python code given in cover.py.

    This document is triggered by some of my friends who are teaching mathe-matics at Calicut University. Even though the �nal result did not match withtheir actual requirement, I am putting this on Internet, with the hope that itmay be useful to somebody. The document just touch upon the subject, notgoing into the details. It is meant for those who want to try out the examplesgiven it in and modify them further for better understanding. Huge amount ofdocumentation is already available on the topics covered in this document, andthe references to many resources on the Internet are given for the bene�t of theserious user.

    This is distributed under the GNU Free Documentation license. The docu-ment is written using LYX, a latex front end, and the sources are also availableto anyone who is interested.

    Ajith KumarIUAC , New Delhiajith at iuac.res.in

  • Contents

    1 An Introduction to Computers 5

    1.1 Hardware & Software . . . . . . . . . . . . . . . . . . . . . . . . 51.2 Hardware Components of a Computer . . . . . . . . . . . . . . . 6

    1.2.1 Central Processing Unit, CPU . . . . . . . . . . . . . . . 61.2.2 Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.2.3 Input/Output Units . . . . . . . . . . . . . . . . . . . . . 7

    1.3 Software Components of a Computer . . . . . . . . . . . . . . . . 71.3.1 Operating System . . . . . . . . . . . . . . . . . . . . . . 7

    1.3.1.1 Files and Directories . . . . . . . . . . . . . . . . 7

    2 Programming in Python 8

    2.1 High Level Languages . . . . . . . . . . . . . . . . . . . . . . . . 82.2 Getting started with Python . . . . . . . . . . . . . . . . . . . . 92.3 Variables and Data Types . . . . . . . . . . . . . . . . . . . . . . 102.4 Compound Data Types . . . . . . . . . . . . . . . . . . . . . . . 11

    2.4.1 Mutable and Immutable Types . . . . . . . . . . . . . . . 112.5 Input from the Keyboard . . . . . . . . . . . . . . . . . . . . . . 122.6 Operators and their Precedence . . . . . . . . . . . . . . . . . . . 132.7 Iteration: while and for loops . . . . . . . . . . . . . . . . . . . . 13

    2.7.1 for loops of Python . . . . . . . . . . . . . . . . . . . . . . 142.8 Conditional Execution: if, elif and else . . . . . . . . . . . . . . . 152.9 Formatted Printing . . . . . . . . . . . . . . . . . . . . . . . . . . 162.10 User de�ned functions . . . . . . . . . . . . . . . . . . . . . . . . 172.11 Python Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . 182.12 File Input/Output . . . . . . . . . . . . . . . . . . . . . . . . . . 192.13 The pickle module . . . . . . . . . . . . . . . . . . . . . . . . . . 202.14 Object Oriented Programming in Python . . . . . . . . . . . . . 212.15 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

    3 Mathematics with Python 26

    3.1 Arrays and Matrices with numpy . . . . . . . . . . . . . . . . . . 273.2 Operations on arrays . . . . . . . . . . . . . . . . . . . . . . . . . 283.3 Plotting with matplotlib . . . . . . . . . . . . . . . . . . . . . . . 283.4 Plotting mathematical functions . . . . . . . . . . . . . . . . . . 30

    3

  • CONTENTS 4

    3.4.1 Sine function and friends . . . . . . . . . . . . . . . . . . 303.4.2 Trouble with Circle . . . . . . . . . . . . . . . . . . . . . 313.4.3 Parametric plots . . . . . . . . . . . . . . . . . . . . . . . 323.4.4 Polar plots . . . . . . . . . . . . . . . . . . . . . . . . . . 33

    3.5 Famous Curves . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333.5.1 Astroid . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333.5.2 Ellipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353.5.3 Spirals of Archimedes and Fermat . . . . . . . . . . . . . 36

    3.6 Power Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373.6.1 Fourier Series . . . . . . . . . . . . . . . . . . . . . . . . . 383.6.2 Polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . 40

    3.7 Matrix Operations . . . . . . . . . . . . . . . . . . . . . . . . . . 413.7.1 array(list) . . . . . . . . . . . . . . . . . . . . . . . . . . . 413.7.2 arange(start, stop, step, dtype = None) . . . . . . . . . . 423.7.3 linspace(start, stop, number of samples) . . . . . . . . . . 423.7.4 zeros(shape, datatype) . . . . . . . . . . . . . . . . . . . 423.7.5 ones(shape, datatype) . . . . . . . . . . . . . . . . . . . . 423.7.6 random.random_sample(shape) . . . . . . . . . . . . . . . 423.7.7 reshape(array, newshape) . . . . . . . . . . . . . . . . . . 423.7.8 Arithmetic Operations . . . . . . . . . . . . . . . . . . . . 433.7.9 cross(array1, array2) . . . . . . . . . . . . . . . . . . . . . 433.7.10 dot(array1, array2) . . . . . . . . . . . . . . . . . . . . . . 443.7.11 array.to�le(�lename), array = from�le(�lename) . . . . . 443.7.12 linalg.inv(array) . . . . . . . . . . . . . . . . . . . . . . . 44

    3.8 Equation solving using matrices . . . . . . . . . . . . . . . . . . . 443.9 Numerical Di�erentiation . . . . . . . . . . . . . . . . . . . . . . 45

    3.9.1 Vectorizing user de�ned functions . . . . . . . . . . . . . . 463.10 Numerical Integration . . . . . . . . . . . . . . . . . . . . . . . . 473.11 Ordinary Di�erential Equations . . . . . . . . . . . . . . . . . . . 48

    3.11.1 Euler method . . . . . . . . . . . . . . . . . . . . . . . . . 493.11.2 Runge-Kutta method . . . . . . . . . . . . . . . . . . . . 49

    3.12 Fractals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513.13 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

  • Chapter 1

    An Introduction to

    Computers

    Computers are being used in diverse areas like o�ce automation, industrial pro-cess control, communications, weather forecasting etc. This is possible becauseof their ability to execute a variety of Programs or Software suitable for these ap-plications. A computer program is a collection of machine language instructionswhich performs simple operations like moving data from one memory locationto another, performing arithmetic operations on numbers etc. A computer isan electronic device capable of processing data according to a set of instructions.The information we feed into the computer are called input data. Manipulatingthe input data according to the instructions is called processing. Any activityusing computers involves the following three steps.

    1. Input : Feeding input data and the instructions into the computer.

    2. Processing : Changing the input data according to the given instructions.

    3. Output : Displays or prints the processed data.

    ExampleProblem: From a list of hundred people and their ages prepare a list of the

    ones above 18 years.Input data : Hundred names and corresponding ages.Processing : Examine each name and age. If age is greater than 18 select

    name and age.Output : Display the selected names and corresponding ages.

    1.1 Hardware & Software

    The set of instructions for processing data is called Software or a computerprogram. The electronic circuits and mechanical parts of the computer are

    5

  • CHAPTER 1. AN INTRODUCTION TO COMPUTERS 6

    called Hardware. Hardware is designed to carry out simple machine languageinstructions, called software. Hardware cannot perform without Software. Therelationship is like a bus and it's driver. The bus is designed to obey the com-mands the driver, given by operating the controls like accelerator, steering wheelor brake. The software gives instructions like add two numbers, move a numberfrom one place to another etc. to the hardware.

    In the next section we will study the Hardware components found in mostof the computers.

    1.2 Hardware Components of a Computer

    Central Processing Unit (CPU), Memory, Input unit and Output unit are themain hardware components of a computer.

    1.2.1 Central Processing Unit, CPU

    CPU1 can be called the brain of the computer. It contains a Control Unitand an Arithmetic and Logic Unit, ALU. The control unit brings the instruc-tions stored in the main memory one by one and acts according to it. It alsocontrols the movement of data between memory and input/output units. TheALU can perform arithmetic operations like addition, multiplication and logicaloperations like comparing two numbers.

    1.2.2 Memory

    Memory stores instructions and data that can be accessed by the CPU. All typesof information are stored as binary numbers. The smallest unit of memory iscalled a binary digit or Bit. It can have a value of zero or one. A group ofeight bits are called a Byte. 1024 bytes is one Kilobyte and 1024 Kilobytesis one Megabyte, MB. A computer has Main and Secondary types of memory.Before processing data and instructions are stored into the main memory. Mainmemory is organized into words of one byte size. CPU can select any memorylocation by using it's address. Main memory is made of semiconductor switchesand are very fast. There are two types of Main Memory. Read Only Memoryand Read Write Memory. Read Write Memory is also called Random AccessMemory. The CPU cannot change the values inside the ROM, it can only readit. All computers contains some programs in ROM which will start runningwhen you switch on the machine.

    Random Access Memory, RAM, is the temporary storage area. Before exe-cuting programs and data are stored into RAM. CPU can read and write RAMat very high speed, millions of times per second. It can select any address with-out following any order. All the contents are lost when power is switched o�. APersonal Computer normally has several hundred megabytes of RAM.

    1The cabinet that encloses most of the hardware is called CPU by some, mainly the com-puter vendors. They are not referring to the actual CPU chip.

  • CHAPTER 1. AN INTRODUCTION TO COMPUTERS 7

    Data and programs to be stored for future use are saved to Secondary mem-ory, mainly devices like Hard disks, �oppy disks, CDROM or magnetic tapes.

    1.2.3 Input/Output Units

    The Input devices are for feeding the input data into the computer. Keyboardis the most common input device. Mouse, scanner etc. are other input devices.

    The processed data is displayed or printed using the output devices. Themonitor screen and printer are the most common output devices.

    1.3 Software Components of a Computer

    Hardware alone cannot perform any work. When powered the CPU looks for theinstructions or software stored inside the main memory. To perform any work weneed to load the appropriate program into the RAM so that the CPU can executeit. An ordinary user cannot do that without the help of a program. Loadingof application programs from disk storage to memory is done by a programcalled the Operating System. OS is loaded when the computer is poweredand it remains in control until the machine is switched o�. Editors, LanguageCompilers, Application programs etc. are the other software components of acomputer.

    1.3.1 Operating System

    Operating system is a software which makes the hardware resources available tothe user. OS can load other programs from disk to the main memory and executethem. It also provides a �le system to use the memory available on the disks.A �le system is a facility provided by the operating system to store informationinside devices like �oppy disk and hard disk. There are many types operatingsystems in use today. OS interacts with the user by accepting typed commandsor by using a Graphical User Interface. GNU/Linux and MS Windows are twopopular operating systems.

    1.3.1.1 Files and Directories

    The naming schemes for disks are di�erent for Windows and GNU/Linux. Win-dows name the drive partitions using letters like C,D,E etc. For Unix like sys-tems the entire �le system is inside a directory represented by a forward slashsymbol '/' and it is called the root directory. GNU/Linux is a multi-user sys-tem and each user has a separate directory to store data and programs, which iscalled the 'home directory' of that user. The user directories are generally insidea directory called '/home'. Users can create �les and sub-directories inside theirhome directory only. Home directory of one user cannot be modi�ed by anotheruser.

  • Chapter 2

    Programming in Python

    In order to solve a problem using a computer it is necessary to evolve a de-tailed and precise step by step method of solution. A set of these precise andunambiguous steps is called an Algorithm. It should begin with steps acceptinginput data and should have steps which gives output data. For implementingan algorithm using computer each of it's steps have to be converted into propermachine language instructions. Doing this process manually is called MachineLanguage Programming. Writing machine language programs need great careand a deep understanding about the internal structure of the computer hard-ware. The programmer has to remember the machine language instruction setalso. High level languages are designed to overcome these di�culties. Usingthem one can create a program without knowing much about the computerhardware.

    Python is a dynamic object-oriented programming language that can be usedfor many kinds of software development. It o�ers strong support for integrationwith other languages and tools, comes with extensive standard libraries, andcan be learned in a few days. Many Python programmers report substantialproductivity gains and feel the language encourages the development of higherquality, more maintainable code. To get to know about the available pythonresources visit www.python.org on the Internet.

    2.1 High Level Languages

    We already learned that to solve a problem we require an algorithm and it hasto be executed step by step. It is possible to express the algorithm using a setof precise and unambiguous notations. The notations selected must be suitablefor the problems to be solved. A high level programming language is a set ofwell de�ned notations which is capable of expressing algorithms.

    In general a high level language should have the following features.

    1. Facility to represent the nature of data. For example it should be able torepresent di�erent data types like characters, integers and real numbers.

    8

  • CHAPTER 2. PROGRAMMING IN PYTHON 9

    In addition to this it should also support a collection similar objects likecharacter strings, arrays and matrices.

    2. Arithmetic and Logical operators that acts on the supported data types.

    3. Control �ow structures for decision making, branching, looping etc.

    4. A set of syntax rules which precisely specify the combination of words andsymbols permissible in the language. Control �ow commands, names ofdata objects etc. are normally represented by words and the operators byusing symbols.

    5. A set of semantic rules which assigns a single, precise and unambiguousmeaning to each syntactically correct statement in the language.

    How do we write a high level language program ?We declare variables of di�erent data types. The variables are represented

    by a name which we give. We write program statements to store input datainto some of these variables. The variables are manipulated by using operatorsto produce the desired output as the program execution proceeds. The control�ow statements specify the order in which computations are performed. Somelanguages also allows grouping of program statements onto statement blocks,functions, subroutines etc. to write well-structured programs.

    Program text written in a high level language is often called the Source Code.It is then translated into the machine language by using translator programs.There are two types of translator programs called interpreters and compilers.Interpreter reads the high level language program line by line, translates andexecutes it. Compilers convert the entire program in to machine language andstores it to a �le which can be executed.

    High level languages make the programming job easier. We can write pro-grams which are machine independent. For the same program di�erent compil-ers can produce machine language code which runs on di�erent types of com-puters and operating systems. BASIC, COBOL, FORTRAN, C, Pascal etc. arepopular high level languages each of them having advantages in di�erent areas.

    2.2 Getting started with Python

    To write any useful program for solving a problem, one has to develop an al-gorithm. The algorithm can be expressed in any suitable high level language.Learning how to develop an algorithm is di�erent from learning a programminglanguage.Learning a programming language means learning the notations, syn-tax and semantic rules of that language. Best way to do this is by writing smallprograms with very simple algorithms. After becoming familiar with the no-tations and rules of the language we can start writing programs to implementmore complicated algorithms. One also has to learn how to enter the the sourcecode into the computer and how to execute it using the Python Interpreter.The details of this process may vary from one system to another.

  • CHAPTER 2. PROGRAMMING IN PYTHON 10

    We will start writing small programs showing the essential elements of thelanguage without going into the details. After that we will study the languagein more details. The �rst part will be done by a working out a series of examplesshowing di�erent aspects of Python. For more information refer to [2].

    Example. hello.py

    Let us start with a program to display the words Hello World on the com-puter screen. The Python program for this contains only a single line as shownbelow.

    print 'Hello World'

    This should be entered into a text �le using any text editor. On a GNU/Linuxsystem you may use a text editor like 'gedit', 'nedit' to create the source �le,call it hello.py . The next step is to call the Python Interpreter to execute thenew program. For that, open a command terminal and type

    python hello.py

    2.3 Variables and Data Types

    As mentioned earlier, any high level programming language should support sev-eral data types. The problem to be solved is represented using variables be-longing to the supported data types. Python supports numeric data types likeintegers, �oating point numbers and complex numbers of di�erent precision. Tohandle character strings, it uses the String data type. Python also supportscompound data types like lists, tuples, dictionaries etc.

    In languages like C, C++ and Java, we need to explicitly de�ne the typeof a variable. This is not required in Python. The data type of a variable isdecided by the value assigned to it. This is called dynamic data typing. Thetype of a particular variable can change during the execution of the program.One type of data can be converted in to another type by type casting.

    The following examples show how to de�ne variables of di�erent data types

    Example: �rst.py

    �'

    This is Python program starting with a multi-line

    comment, enclosed within three single quotes.

    In a single line, anything after a # sign is a comment

    �'

    x = 10

    print x, type(x) #print x and its type

    y = 10.4

    print y, type(y)

    z = 3 + 4j

  • CHAPTER 2. PROGRAMMING IN PYTHON 11

    print z, type(z)

    s1 = 'I am a String '

    s2 = 'me too'

    print s1, s2, type(s1)

    Save this to a �le named �rst.py and run it using the Python Interpreter.

    2.4 Compound Data Types

    In the previous example the �rst three variables used are of numeric type. Thevariables s1 and s2 contain variable number of character data. String can beenclosed in either double or single quotes, using same at both ends. The individ-ual elements can be accessed using indexing. Python also supports more �exiblecompound data types likelists, tuples and dictionaries. Being an object orientedlanguage, it is very easy to create new user de�ned data types in Python. Theexample below shows how to index elements of a compound data.

    Example: second.py

    s = 'My name'

    print s[0] # will print M

    print s[3]

    print s[-1] # will print the last element

    a = [12, 3.4, 'haha'] # List type

    print a, type(a)

    print a[0]

    2.4.1 Mutable and Immutable Types

    There is one major di�erence between String and List types, List is mutablebut String is not. We can change the value of an element in a list, add newelements to it and remove any existing element. This is not possible with Stringtype. Tuple is another data type similar to List, except that it is immutable.The following example will clarify these aspects.

    Example: third.py

    s = [3, 3.5, 234] # make a list

    s[2] = 'haha' # Change an element

    a = (4, 3.2, 'hi') # Tuple type

    a[0] = 6 # Will give ERROR

    x = 'myname' # String type

    x[1] = 2 # Will give ERROR

    The List data type is very �exible, an element of a list can be another list. Wewill be using lists extensively in the coming chapters.

  • CHAPTER 2. PROGRAMMING IN PYTHON 12

    2.5 Input from the Keyboard

    Since most of the programs require some user input from the keyboard, let usintroduce this feature before proceeding further. There are mainly two functionsused for this purpose, input() for numeric type data and raw_input() for stringtype data. A message to be displayed can be given as an argument while callingthese functions.

    Example: kin.py

    x = input('Enter an integer ')

    y = input('Enter one more ')

    print 'The sum is ', x + y

    s = raw_input('Enter a String ')

    print 'You entered ', s

    It is also possible to read more than one variables using a single input() state-ment. String type data read using raw_input() may be converted into integeror �oat type if they contain only the valid characters. In order to show thee�ect of conversion explicitly, we multiply the variables by 2 before printing.Multiplying a String by 2 prints it twice. If you enter a non-numeric characterstring, the conversion to �oat will give an error.

    Example: kin2.py

    x,y = input('Enter x and y separated by comma ')

    print 'The sum is ', x + y

    s = raw_input('Enter a decimal number ')

    print 'Your input string x 2 = ', s

    a = float(s)

    print a * 2

    We have learned about the basic data types of Python and howto get input datafrom the keyboard. This is enough to try some simple problems and algorithmsto solve them.

    Example: area.py

    pi = 3.1416

    r = input('Enter Radius ')

    a = pi * r ** 2 #A = πr2

    print 'Area = ', a

    The above example calculates the area of a circle. Line three calculatesr2using the exponentiation operator ∗∗, and multiply it with π using themultiplication operator ∗. r2is evaluated �rst because ** has higherprecedence than *, otherwise the result will be (πr)2.

  • CHAPTER 2. PROGRAMMING IN PYTHON 13

    Operator Description Sample Expression Resultor Boolean OR 0 or 4 4and Boolean AND 3 and 0 0not x Boolean NOT not 0 True

    in, not in Membership tests 3 in [2.2,3,12] True=, !=, == Comparisons 2 > 3 False

    | Bitwise OR 1 | 2 3^ Bitwise XOR 1 ^ 5 4& Bitwise AND 1 & 3 1

    Bitwise Shifting 1

  • CHAPTER 2. PROGRAMMING IN PYTHON 14

    Well, we are stopping here and looking for a better way to do this job. Thesolution is to use the while loop of Python. We will de�ne a variable x andassign it an initial value of 1. Print x ∗ 8 and increment the value of x. Thisprocess will be repeated until the value of x becomes greater than 10.

    Example: table.py

    x = 1

    while x

  • CHAPTER 2. PROGRAMMING IN PYTHON 15

    Example: forloop3.py

    mylist = range(5,51,5)

    for item in mylist:

    print item

    In some cases, we may need to traverse the list to modify some or all of theelements. This can be done by �nding the length of the list and a for loop withthe range function. For example, the program forloop4.py zeros all the negativenumbers of the list.

    Example: forloop4.py

    a = [2, 5, -3, 4, -2, 12]

    size = len(a)

    for k in range(size):

    if a[k] < 0:

    a[k] = 0

    print a

    2.8 Conditional Execution: if, elif and else

    In some cases, we may need to execute some section of the code only if certainconditions are true. Python implements this feature using the if, elif and elsekeywords, as shown in the next example.

    Example: big.py

    x = input('Enter a number ')

    if x > 10:

    print 'Bigger Number'

    elif x < 10:

    print 'Smaller Number'

    else:

    print 'Same Number'

    The next example uses while and if keywords in the same program. Note thelevel of indentation when the if statement comes inside the while loop. The ifstatement and the corresponding else must be aligned.

    Example: big2.py

    x = 1

    while x < 11:

    if x < 5:

    print 'Samll ', x

    else:

    print 'Big ', x

    print 'Done'

  • CHAPTER 2. PROGRAMMING IN PYTHON 16

    We can use the break statement to come out of a loop, if some condition is met.

    Example: big3.py

    x = 1

    while x < 100:

    print x

    if x > 10:

    print 'Enough of this'

    break

    x = x + 1

    print 'Done'

    Now let us write a program to �nd out the largest positive number entered by theuser. The algorithm works in the following manner. To start with, we assumethat the largest number entered is zero. After reading a number, the programchecks whether it is bigger than the current value of the largest number. If sothe value of the largest number is replaced with it. The program terminateswhen the user enters zero.

    Example: max.py

    max = 0

    while 1: # Infinite loop

    x = input('Enter a number ')

    if x > max:

    max = x

    if x == 0:

    print max

    break

    2.9 Formatted Printing

    Formatted printing is done by using a format string followed by the % operatorand the values to be printed. If format requires a single argument, values may bea single non-tuple object. Otherwise, values must be a tuple (just place theminside parenthesis, separated by commas) with exactly the number of itemsspeci�ed by the format string.

    Example: format.py

    a = 2.0 /3 # 2/3 will print zero

    print a

    print 'a = %5.3f' %(a) # upto 3 decimal places

    Data can be printed in various formats. The conversion types are summarizedin the following table. There are several �ags that can be used to modify theformatting, like justi�cation, �lling etc.

  • CHAPTER 2. PROGRAMMING IN PYTHON 17

    Conversion Conversion Example Result

    d , i signed Integer '%6d'%(12) ' 12'f �oating point decimal '%6.4f'%(2.0/3) 0.667e �oating point exponential '%6.2e'%(2.0/3) 6.67e-01x hexadecinal '%x'%(16) 10o octal '%o'%(8) 10s string '%s'%('abcd') abcd0d modi�ed 'd' '%05d'%(12) 00012

    Table 2.2: Formatted Printing in Python

    The following example shows some of the features available with formattedprinting.

    Example: format2.py

    a = 'justify as you like'

    print '%30s'%a # right justified

    print '%-30s'%a # minus sign for left justification

    for k in range(1,11): # A good looking table

    print '5 x %2d = %2d' %(k, k*5)

    The output of format2.py is given below.

    justify as you like

    justify as you like

    5 x 1 = 5

    5 x 2 = 10

    5 x 3 = 15

    5 x 4 = 20

    5 x 5 = 25

    5 x 6 = 30

    5 x 7 = 35

    5 x 8 = 40

    5 x 9 = 45

    5 x 10 = 50

    2.10 User de�ned functions

    Large programs need to be divided into logical subsections. Python allows youto de�ne functions using the keyword def . One can specify more than onevariables in the return statement, separated by commas. The function willreturn a tuple containing those variables.

    Example func.py

  • CHAPTER 2. PROGRAMMING IN PYTHON 18

    def sum(a,b): # a trivial function

    return a + b

    print sum(3, 4)

    Example factor.py

    def factorial(n): # a recursive function

    if n == 0:

    return 1

    else:

    return n * factorial(n-1)

    print factorial(10)

    Python functions can have a variable argument list, the same function canbe called with di�erent number of arguments. The following example showsa function named power() that does exponentiation, but the default value ofexponent is set to 2.

    Example power.py

    def power(mant, exp = 2.0):

    return mant ** exp

    print power(5., 3)

    print power(4.) # prints 16

    2.11 Python Modules1

    One of the major advantages of Python is the availability of large number oflibraries, called modules, for graphics, networking, scienti�c computation etc.Modules are loaded by using the keyword import . Several ways of using importis explained below.

    Example mathsin.py

    import math

    print math.sin(0.5) # module_name.method_name

    Example mathsin2.py

    import math as m # Give another name for math

    print m.sin(0.5) # Refer by the new name

    1While giving names to your Python programs, make sure that you are not directly orindirectly importing any Python module having same name. For example, if you create aprogram named math.py and keep it in your working directory, the import math statementfrom any other program started from that directory will try to import your �le named math.pyand give error. If you ever do that by mistake, delete all the �les with .pyc extension fromyour directory.

  • CHAPTER 2. PROGRAMMING IN PYTHON 19

    Example mathlocal.py

    from math import sin # sin is imported as local

    print sin(0.5)

    Example mathlocal2.py

    from math import * # import everything from math

    print sin(0.5)

    In the third and fourth cases, we need not type the module name every time.But there could be trouble if two modules imported has a function with samename. In the program con�ict.py, the sin function from numpy is capable ofhandling array arguments. After importing math.py, line 4, the sin functionfrom math module replaces the one from numpy. The error occurs because thesin from math cannot handle an array argument.

    Example con�ict.py

    from numpy import *

    x = linspace(0, 5, 10) # make a 10 element array

    print sin(x) # sin of scipy can handle arrays

    from math import * # sin of math will be called now

    print sin(x) # will give ERROR

    2.12 File Input/Output

    Disk �les can be opened using the function named open() that returns a �leobject. Files can be opened for reading or writing. There are several methodsbelonging to the �le class that can be used for reading and writing data.

    Example w�le.py

    f = open('test.dat' , 'w')

    f.write ('This is a test file')

    f.close()

    Above program creates a new �le named 'test.dat' (any existing �le with thesame name will be deleted) and writes a string to it. The following programopens this �le for reading the data.

    Example r�le.py

    f = open('test.dat' , 'r')

    print f.read()

    f.close()

    Note that the data written/read are character strings. read() function can alsobe used to read a �xed number of characters, as shown below.

  • CHAPTER 2. PROGRAMMING IN PYTHON 20

    Example r�le2.py

    f = open('test.dat' , 'r')

    print f.read(7) # get first seven characters

    print f.read() # get the remaining ones

    f.close()

    Now we will examine how to read a text data from a �le and convert it intonumeric type. First we will create a �le with a column of numbers.

    Example w�le2.py

    f = open('data.dat' , 'w')

    for k in range(1,4):

    s = '%3d\n' %(k)

    f.write(s)

    f.close()

    The contents of the �le created will look like this.123

    Now we write a program to read this �le, convert the string type data tointeger type, and print the numbers.

    Example r�le3.py

    f = open('data.dat' , 'r')

    while 1: # infinite loop

    s = f.readline()

    if s == � : # Empty string means end of file

    break # terminate the loop

    m = int(s) # Convert to integer

    print m * 5

    f.close()

    2.13 The pickle module

    In the previous section we have seen that the data going to �le is always treatedas character strings. To preserve the data type information, we can use thepickle module, as shown below.

    Example pickledump.py

    import pickle

    f = open('test.pck' , 'w')

    pickle.dump(12.3, f) # write a float type

    f.close()

  • CHAPTER 2. PROGRAMMING IN PYTHON 21

    Now write another program to read it back from the �le and check the datatype.

    Example pickleload.py

    import pickle

    f = open('test.pck' , 'r')

    x = pickle.load(f)

    print x , type(x) # check the type of data read

    f.close()

    2.14 Object Oriented Programming in Python

    OOP is a programming paradigm that uses objects (Structures consisting ofvariables and methods) and their interactions to design computer programs.OO design focusses on:

    • Encapsulation: dividing the code into a public interface, and a privateimplementation of that interface

    • Polymorphism: the ability to overload standard operators so that theyhave appropriate behavior based on their context

    • Inheritance: the ability to create subclasses that contain specializations oftheir parents

    Before going to the new concepts, let us recollect what we have learned so far.We have learned how to write programs using the built-in data types like int,�oat, str etc. We have seen that the e�ect of operators on di�erent data typesis prede�ned. For example 2∗3 results in 6 and 2∗′ abc′ results in ′abcabc′. Thisbehavior has been decided beforehand, based on some logic, by the languagedesigners.

    One of the key features of OOP is the ability to create user de�ned datatypes. The user will specify, how the new data type will behave under theexisting operators like add, subtract etc. and also de�ne methods that willbelong to the new data type (or Class). We will start with a simple examplecloth.py that de�nes a Class named clothing. Please note that Python uses thekeyword self to denote that the variable belongs to the same object that we aremanipulating.

    Example cloth.py

    class clothing:

    def __init__(self,colour, rate):

    self.colour = colour

    self.rate = rate

    def getcolour(self):

  • CHAPTER 2. PROGRAMMING IN PYTHON 22

    return self.colour

    cheapblue = clothing('blue', 20.0)

    costlyred = clothing('red', 100.0)

    print cheapblue.rate

    print costlyred

    This program generates the following output:

    20.0

    In cloth.py, we de�ne a Class named clothing, using the class keyword. Wealso created two Objects, cheapblue and costlyred, as instances (or objects) ofthe Class clothing. The __init__ function is called the constructor, that isexecuted everytime when we create a new object, using a class. From the outputof this program we can see the that the print function does not know how tohandle this new data type. We can specify it by overloading the __str__function for this class. The __str__ function is responsible for converting anyobject to a string for printing, as shown in cloth2.py.

    Example cloth2.py

    class clothing:

    def __init__(self,colour, rate):

    self.colour = colour

    self.rate = rate

    def getcolour(self):

    return self.colour

    def __str__(self):

    return '%s Cloth at Rs. %6.2f per sqmtr'%(self.colour, self.rate)

    cheapblue = clothing('blue', 20.0)

    costlyred = clothing('red', 100.0)

    print cheapblue.rate

    print costlyred

    The modi�ed program is able to print the details of the atom as:

    20.0

    red Cloth at Rs. 100.00 per sqmtr

    Similarly you can rede�ne the other operators like __add__, __sub__, __mul__,__div__ etc. to de�ne the arithmetic operations provided they make somesense.

    We can derive a subclass from an already de�ned class. For example, theprogram pants.py creates a subclass pants using the parent class named clothes.Inside the __init__ function of the subclass, we need to call the __init__of the parent class. We have not written a __str__ method for pants. The__str__ function of the parent class will be used for printing the subclass insuch cases.

  • CHAPTER 2. PROGRAMMING IN PYTHON 23

    Example pants.py

    class clothing:

    def __init__(self,colour, rate):

    self.colour = colour

    self.rate = rate

    def getcolour(self):

    return self.colour

    def __str__(self):

    return '%s Cloth at Rs. %6.2f per sqmtr'%(self.colour, self.rate)

    class pants(clothing):

    def __init__(self, cloth, size, labour):

    self.labour = labour

    self.size = size

    clothing.__init__(self,cloth.colour, cloth.rate)

    def getcost(self):

    return self.rate * self.size + self.labour

    costlyred = clothing('red', 100.0)

    smallpant = pants(costlyred, 1.5, 100)

    print smallpant.getcost()

    print smallpant

    This section is very small and lot more is required to be written. Read reference[2] for more details.

    2.15 Exercises

    1. De�ne 2 + 5j and 2 − 5j as complex numbers , and �nd their product.Verify the result by de�ning the real and imaginary parts separately andusing the multiplication formula.

    2. De�ne a string s = 'mary had a little lamb'.a) print it reverseb) print the fourth word of s , using indexing.c) Explore the string methods like count, lower, �nd etc. using this string

    3. Write a program to evaluate y=√

    2.3a + a2 + 34.5 for a = 1, 2 and 3.

    4. Write the multiplication table of 12 using while and for loops.

    5. Print the powers of 2 upto 1024 using a for loop. (total two lines of code)

    6. De�ne the list a = [123, 12.4, 'haha', 3.4]a) print all members using a for loopb) print the �oat type members ( use type() function)c) insert a member after 12.4d) append more members

  • CHAPTER 2. PROGRAMMING IN PYTHON 24

    7. Make a list containing 10 members using a for loop.

    8. Write a program to �nd the sum of �ve numbers read from the keyboard.

    9. Write a program to read numbers from the keyboard until their sum ex-ceeds 200. Modify the program to ignore numbers greater than 99.

    10. Generate a formatted multiplication table and write it to a �le.

    11. Make a list and write it to a �le using the pickle module.

  • Bibliography

    [1] http://www.python.org/

    [2] http://greenteapress.com/thinkpython/thinkpython.html

    25

  • Chapter 3

    Mathematics with Python

    The objective of this chapter is to demonstrate how we can learn mathemat-ics with the help of Python programming language. We will write Pythonprograms for plotting mathematical functions, solving equations and for doingmathematical operations using numerical methods. We will try to keep the pro-grams as simple as possible. Most of the operations require working with oneor two dimensional matrices. Functions capable of working directly on arraysand matrices makes the code very simple. In the beginning we will use the mathmodule, maily to realize its limitations, and then explore packages like numpy,scipy, matplotlib etc.

    The �rst example generates xy coordinates to plot a sine wave, plotting willbe done using some external program. Enter the following code to a �le namedsine.py , using any text editor.

    Example sine.py

    import math

    x = 0.0

    while x < math.pi * 4:

    print x , math.sin(x)

    x = x + 0.1

    The output to the screen can be redirected to a �le as shown below, from thecommand prompt. You can plot the data using some program like xmgrace.

    $ python sine.py > sine.dat$ xmgrace sine.datThere are two things we do not like in the above program. One is to deal

    with the loops to generate the data and the other is to use an external programto plot the data.

    26

  • CHAPTER 3. MATHEMATICS WITH PYTHON 27

    3.1 Arrays and Matrices with numpy

    We need some Python module that can handle arrays and matrices. We will usethe module numpy that supports operations on compound data types like arraysand matrices. The matplotlib package will be used for plotting.First thing tolearn is how to create arrays and matrices using the numpy package. Pythonlists can be converted into multi-dimensional arrays. There are several otherfunctions that can be used for creating matrices. The numpy package containsmore than 400 functions [6], but we will be using only few of them. In theexamples below, we will import numpy functions as local. Since it is the onlypackage used there is no possibility of any function name con�icts.

    Example numpy1.py

    from numpy import *

    x = array( [1,2] ) # Make array from list

    print x , type(x)

    In the above example, we have created an array from a list. There are severalfunction that can be used for creating di�erent types of arrays and matrices, asshown in the following examples.

    Example numpy2.py

    from numpy import *

    a = arange(1.0, 2.0, 0.1) # start, stop & step

    print a

    b = linspace(1,2,11)

    print b

    c = ones(5)

    print c

    d = zeros(5)

    print d

    e = random.rand(5)

    print e

    Output of this program will look like;[ 1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9][ 1. 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2. ][ 1. 1. 1. 1. 1.][ 0. 0. 0. 0. 0.][ 0.89039193 0.55640332 0.38962117 0.17238343 0.01297415]The arange() function takes start, stop and step as arguments. The total

    number of elements will be (stop − start)/step. The linspace() function takesstart, stop and number of points as arguments.

    So far we have only made one-dimensional arrays. We can also make multi-dimensional arrays. Remember that a member of a list can be another list. Thefollowing example shows how to make a two dimensional array.

  • CHAPTER 3. MATHEMATICS WITH PYTHON 28

    Example numpy3.py

    from numpy import *

    a = [ [1,2] , [3,4] ] # make a list of lists

    x = array(a) # and convert to an array

    print a

    We can also make multi-dimensions arrays by reshaping a one-dimensional array.

    Example numpy4.py

    from numpy import *

    a = arange(10)

    print a

    a = a.reshape(5,2) # 5 rows and 2 columns

    print a

    3.2 Operations on arrays

    One of the objectives of using the array data type is to perform operationslike addition, multiplication etc. without explicitly accessing the individual ele-ments. When you multiply and array by a number, each element get multipliedby that number. To understand the behavior of array arithmetic, examine theresults of the following example program.

    Example numpy5.py

    from numpy import *a = array([ [1.0, 2.0] , [3.0, 4.0] ]) # make a numpy arrayprint aprint a * 5print a * aprint a / anumpy supports several functions for doing matrix algebra, that will be

    discussed later in detail. The mathematical functions like sine, cosine etc. ofnumpy accepts array objects as arguments and return the results as arraysobjects.

    3.3 Plotting with matplotlib

    Matplotlib is a python 2D plotting library which produces publication quality�gures in a variety of hardcopy formats. Matplotlib can be used in Pythonprograms. You can generate plots, histograms, power spectra, bar charts, er-rorcharts, scatterplots, etc, with just a few lines of code and have full control ofline styles, font properties, axes properties, etc.

  • CHAPTER 3. MATHEMATICS WITH PYTHON 29

    If you import it as pylab, you get all the plotting functions from matplot-plotlib.pyplot as well as non-plotting functions from matplotlib.mlab and alsofrom the numpy module. We will be using matplotlib in the pylab mode so thatwe need not import numpy explicitly. Let us start with some simple plots tobecome familiar with matplotlib.

    Example plot1.py

    from pylab import *

    data = [1,2,5]

    plot(data)

    show()

    In the above example, the x-axis of the three points is taken from 0 to 2. Wecan specify both the axes as shown below.

    Example plot2.py

    from pylab import *

    x = [1,2,5]

    y = [4,5,6]

    plot(x,y)

    show()

    By default, the color is blue and the line style is continuous. This can be changedby an optional argument after the coordinate data, which is the format stringthat indicates the color and line type of the plot. The default format string is`b-` (blue, continuous line). Let us rewrite the above example to plot using redcircles. We will also set the ranges for x and y axes and label them.

    Example plot3.py

    from pylab import *

    x = [1,2,5]

    y = [4,5,6]

    plot(x,y,'ro')

    xlabel('x-axis')

    ylabel('y-axis')

    axis([0,6,1,7])

    show()

    The �gure 3.1 shows two di�erent plots in the same window, using di�erentmarkers and colors.

    Example plot4.py

    from pylab import *

    t = arange(0.0, 5.0, 0.2)

    plot(t, t**2,'x') # t2

    plot(t, t**3,'ro') # t3

    show()

  • CHAPTER 3. MATHEMATICS WITH PYTHON 30

    0 1 2 3 4 50

    20

    40

    60

    80

    100

    120

    Figure 3.1: Output of plot4.py

    We have just learned how to draw a simple plot using the pylab interface ofmatplotlib. To learn more about it refer to the matplotlib tutorial [1].

    3.4 Plotting mathematical functions

    One of our objectives is to understand di�erent mathematical functions by plot-ting them graphically. We will use the arange, linspace and logspace functionsfrom numpy to generate the input data and the vectorized functions to calculatethe value of the mathematical functions. The results are plotted using the py-plot subpackage from matplotlib. To generate the input data, we are using thelinspace() or arange() functions from numpy. For arange(), the third argumentis the stepsize and the total number of points is calculated from start, stop andstepsize. In the case of linspace(), we provide start, stop and the total numberof points. The step size is calculated from these three parameters. Please notthat to create a data set ranging from 0 to 1 (including both) with a stepsize of0.1, we need to specify linspace(0,1,11) and not linspace(0,1,10).

    3.4.1 Sine function and friends

    Let the �rst example be the familiar sine function. The input data is from −π to+π radians1. To make it a bit more interesting we are plotting sinx2 also. The

    1Why do we need to give the angles in radians and not in degrees. Angle in radian is thelength of the arc de�ned by the given angle, with unit radius. Degree is just an arbitrary unit.

  • CHAPTER 3. MATHEMATICS WITH PYTHON 31

    �4�3�2�1 0 1 2 3 4�1.0�0.50.0

    0.5

    1.0

    �10 �5 0 5 10�10�50

    5

    10

    Figure 3.2: (a) Output of sin.py (b) Output of circ.py .

    objective is to explain the concept of odd and even functions. Mathematically,we say that a function f(x) is even if f(x) = f(−x) and is odd if f(−x) = −f(x).Even functions are functions for which the left half of the plane looks like themirror image of the right half of the plane. From the �gure 3.2(a) you can seethat sinx is odd and sinx2 is even.

    Example npsin.py

    from pylab import *

    x = linspace(-pi, pi , 200)

    y = sin(x)

    y1 = sin(x*x)

    plot(x,y)

    plot(x,y1,'r')

    show()

    Exercise: Modify the program npsin.py to plot sin2 x , cos x, sinx3 etc.

    3.4.2 Trouble with Circle

    Equation of a circle is x2 + y2 = a2 , where a is the radius and the circleis located at the origin of the coordinate system. In order to plot it usingCartesian coordinates, we need to express y in terms of x, and is given by

    y =√

    a2 − x2

    We will create the x-coordinates ranging from −a to +a and calculate thecorresponding values of y. This will give us only half of the circle, since foreach value of x, there are two values of y (+y and -y). The following programcirc.py creates both to make the complete circle as shown in �gure 3.2(b). Anymultivalued function will have this problem while plotting. Such functions canbe plotted better using parametric equations or using the polar plot options, asexplained in the coming sections.

  • CHAPTER 3. MATHEMATICS WITH PYTHON 32

    �10 �5 0 5 10�10�50

    5

    10

    �20�15�10�5 0 5 10 15 20�20�15�10�50510

    15

    20

    Figure 3.3: (a)Output of circpar.py. (b)Output of arcs.py

    Example circ.py

    from pylab import *

    a = 10.0

    x = linspace(-a, a , 200)

    yupper = sqrt(a**2 - x**2)

    ylower = -sqrt(a**2 - x**2)

    plot(x,yupper)

    plot(x,ylower)

    show()

    3.4.3 Parametric plots

    The circle can be represented using the equations x = a cos θ and y = a sin θ .To get the complete circle θ should vary from zero to 2π radians. The outputof circpar.py is shown in �gure 3.3(a).

    Example circpar.py

    from pylab import *

    a = 10.0

    th = linspace(0, 2*pi, 200)

    x = a * cos(th)

    y = a * sin(th)

    plot(x,y)

    show()

    Changing the range of θ to less than 2π radians will result in an arc. Thefollowing example plots several arcs with di�erent radii. The for loop willexecute four times with the values of radius 5,10,15 and 20. When the value ofradius a is 5, θ will range from 0 to 0.5π (450) . For the next three values it willbe π, 1.5πand2π respectively. The output is shown in �gure 3.3(b).

  • CHAPTER 3. MATHEMATICS WITH PYTHON 33

    Example arcs.py

    from pylab import *

    a = 10.0

    for a in range(5,21,5):

    th = linspace(0, pi * a/10, 200)

    x = a * cos(th)

    y = a * sin(th)

    plot(x,y)

    show()

    3.4.4 Polar plots

    Polar coordinates locate a point on a plane with one distance and one angle.The distance `r' is measured from the origin. The angle θ is measured from someagreed starting point. Use the positive part of the x−axis as the starting pointfor measuring angles. Measure positive angles anti-clockwise from the positivex − axis and negative angles clockwise from it.

    Matplotlib supports polar plots, using the polar(θ, r) function. Let us plota circle using polar(). For every point on the circle, the value of radius is thesame but the polar angle θ changes from 0to 2π. Both the coordinate argumentsmust be arrays of equal size. Since θ is having 100 points , r also must havethe same number. This array can be genearted using the ones() function. Theaxis([θmin, θmax, rmin, rmax) function is used for setting the scale.

    Example polar.py

    from pylab import *

    th = linspace(0,2*pi,100)

    r = 5 * ones(100) # radius = 5

    axis([0, 2*pi, 0, 10])

    polar(th,r)

    show()

    3.5 Famous Curves

    Connetion between di�erent branches of mathematics like trignometry, algebraand geometry can be understood by geometrically representing the equations.You will �nd a large number of equations generating geometric patterns havinginteresting symmetries in the history of mathematics. A collection of them isavailable on the Internet [2][3]. We will select some of them and plot here.Exploring them further is left as an exercise to the reader.

    3.5.1 Astroid

    The astroid was �rst discussed by Johann Bernoulli in 1691-92. It also appearsin Leibniz's correspondence of 1715. It is sometimes called the tetracuspid for

  • CHAPTER 3. MATHEMATICS WITH PYTHON 34

    0.0 0.5 1.0 1.5 2.00.0

    0.5

    1.0

    1.5

    2.0

    �2.0�1.5�1.0�0.5 0.0 0.5 1.0 1.5 2.0�2.0�1.5�1.0�0.50.00.51.0

    1.5

    2.0

    Figure 3.4: (a)Output of astro.py (b) Output of astropar.py

    the obvious reason that it has four cusps. A circle of radius 1/4 rolls aroundinside a circle of radius 1 and a point on its circumference traces an astroid.The Cartesian equation is

    x23 + y

    23 = a

    23 (3.1)

    The parametric equations are

    x = a cos3(t), y = a sin3(t) (3.2)

    In order to plot the curve in the Cartesian system, we rewrite equation 3.1as

    y = (a23 − x 23 ) 32

    The program astro.py plots the part of the curve in the �rst quadrant. Theprogram astropar.py uses the parametric equation and plots the complete curve.Both are shown in �gure 3.4

    Example astro.py

    from pylab import *

    a = 2

    x = linspace(0,a,100)

    y = ( a**(2.0/3) - x**(2.0/3) )**(3.0/2)

    plot(x,y)

    show()

    Example astropar.py

    from pylab import *

    a = 2

    t = linspace(-2*a,2*a,101)

    x = a * cos(t)**3

    y = a * sin(t)**3

    plot(x,y)

    show()

  • CHAPTER 3. MATHEMATICS WITH PYTHON 35

    �2.0�1.5�1.0�0.5 0.0 0.5 1.0 1.5 2.0�3�2�101

    2

    3

    �2.0�1.5�1.0�0.5 0.0 0.5 1.0 1.5 2.0�3�2�101

    2

    3

    Figure 3.5: (a) Output of ellipse.py. (b) Output of lissa.py

    3.5.2 Ellipse

    The ellipse was �rst studied by Menaechmus [4] . Euclid wrote about the ellipseand it was given its present name by Apollonius. The focus and directrix of anellipse were considered by Pappus. Kepler, in 1602, said he believed that theorbit of Mars was oval, then he later discovered that it was an ellipse with thesun at one focus. In fact Kepler introduced the word focus and published hisdiscovery in 1609.

    The Cartesian equation is

    x2

    a2+

    y2

    b2= 1 (3.3)

    The parametric equations are

    x = a cos(t), y = b sin(t) (3.4)

    The program ellipse.py uses the parametric equation to plot the curve. Mod-ifying the parametric equations will result in Lissajous �gures. The output ofellipse.py and lissa.py are shown in �gure 3.5.

    Example ellipse.py

    from pylab import *

    a = 2

    b = 3

    t = linspace(0, 2 * pi, 100)

    x = a * sin(t)

    y = b * cos(t)

    plot(x,y)

    show()

    Example lissa.py

  • CHAPTER 3. MATHEMATICS WITH PYTHON 36

    0�45�90�135�

    180�225�

    270�315�10

    2030

    4050

    6070

    0�45�90�135�

    180�225�

    270�315�5

    1015

    Figure 3.6: (a)Archimedes Spiral (b) Fermat's Spiral

    from pylab import *

    a = 2

    b = 3

    t= linspace(0, 2*pi,100)

    x = a * sin(2*t)

    y = b * cos(t)

    plot(x,y)

    x = a * sin(3*t)

    y = b * cos(2*t)

    plot(x,y)

    show()

    The lissajous curves are closed if the ratio of the arguments for sine and cosinefunctions is an integer. Otherwise open curves will result, both are shown in�gure 3.5(b). Modify the program lissa.py to study it further.

    3.5.3 Spirals of Archimedes and Fermat

    The spiral of Archimedes is represented by the equation r = aθ. Fermats Spiralis given by r2 = a2θ. The output of archi.py and fermat.py are shown in �gure3.6.

    Example archi.py

    from pylab import *

    a = 2

    th= linspace(0, 10*pi,200)

    r = a*th

    polar(th,r)

    axis([0, 2*pi, 0, 70])

    show()

    Example fermat.py

  • CHAPTER 3. MATHEMATICS WITH PYTHON 37

    �4�3�2�1 0 1 2 3 4�6�4�202

    4

    6

    �4�3�2�1 0 1 2 3 4�4�202

    4

    Figure 3.7: Functions evaluated using power series. (a)Sine (b) Cosine

    from pylab import *

    a = 2

    th= linspace(0, 10*pi,200)

    r = sqrt(a**2 * th)

    polar(th,r)

    polar(th, -r)

    show()

    There are dozens of other famous curves whose details are available on theInternet. It may be an interesting exercise for the reader. For more details referto [3, 2, 5]on the Internet. The program cover.py that generated the cover pageis listed below.

    from pylab import *

    th = linspace(0, 10*pi,1000)

    r = 4* sin(8*th)

    polar(th,r)

    r = sqrt(th)

    polar(th,r)

    polar(th, -r)

    show()

    3.6 Power Series

    Trignometric functions like sine and cosine sounds very familiar to all of us,due to our interaction with them since high school days. However most ofus would �nd it di�cult to obtain the numerical values of , say sin 50, withouttrigonometric tables or a calculator. We know that di�erentiating a sine functiontwice will give you the original function, with a sign reversal, which implies

    d2y

    dx2+ y = 0

  • CHAPTER 3. MATHEMATICS WITH PYTHON 38

    which has a series solution of the form

    y = a0∞∑

    n=0

    (−1)n x2n

    (2n)!+ a1

    ∞∑n=0

    (−1)n x2n+1

    (2n + 1)!(3.5)

    These are the Maclaurin series for sine and cosine functions. The followingcode plots several terms of the sine series and their sum.

    Example series_sin.py

    from pylab import *

    from scipy import factorial

    x = linspace(-pi, pi, 50)

    y = zeros(50)

    for n in range(5):

    term = (-1)**(n) * (x**(2*n+1)) / factorial(2*n+1)

    y = y + term

    plot(x,term)

    plot(x, y, '+b')

    plot(x, sin(x),'xr') # compare with the real one

    show()

    The output of series_sin.py is shown in �gure 3.7(a). Each term of the seriesis plotted as continuous lines. The �nal result obtained by the series is plottedusing + marker and for comparison the sin function from the library is plottedusing the x marker. Replacing the expression to calculate the series terms by(−1) ∗ ∗n ∗ (x ∗ ∗(2 ∗ n))/factorial(2 ∗ n) will give the cosine curve as shown in�gure 3.7(b) . This is left as an exercise to the reader.

    The value calculated by using the series becomes closer to the actual valuewith more and more number of terms. The error can be obtained by adding thefollowing lines to series_sin.py and the e�ect of number of terms on the errorcan be studied.

    err = y - sin(x)

    plot(x,err)

    for k in err:

    print k

    3.6.1 Fourier Series

    A Fourier series is an expansion of a periodic function f(x) in terms of anin�nite sum of sines and cosines. Fourier series make use of the orthogonalityrelationships of the sine and cosine functions. The computation and study ofFourier series is known as harmonic analysis and is extremely useful as a way tobreak up an arbitrary periodic function into a set of simple terms that can beplugged in, solved individually, and then recombined to obtain the solution to

  • CHAPTER 3. MATHEMATICS WITH PYTHON 39

    �4�3�2�1 0 1 2 3 4�2.0�1.5�1.0�0.50.00.51.0

    1.5

    2.0

    0 1 2 3 4 5 6 7�1.0�0.50.0

    0.5

    1.0

    Figure 3.8: Sawtooth and Square waveforms generated using Fourier series.

    the original problem or an approximation to it to whatever accuracy is desiredor practical.

    The examples below shows how to generate a square wave and sawtoothwave using this technique. To make the output better, increase the numberof terms by changing the argument of the range function. The output of theprograms are shown in �gure 3.8.

    Example fourier_square.py

    from pylab import *

    N = 100 # number of points

    x = linspace(0.0, 2 * pi, N)

    y = zeros(N)

    for n in range(5):

    term = sin((2*n+1)*x) / (2*n+1)

    y = y + term

    plot(x,y)

    show()

    Example fourier_sawtooth.py

    from pylab import *

    N = 100 # number of points

    x = linspace(-pi, pi, N)

    y = zeros(N)

    for n in range(1,10):

    term = (-1)**(n+1) * sin(n*x) / n

    y = y + term

    plot(x,y)

    show()

  • CHAPTER 3. MATHEMATICS WITH PYTHON 40

    Figure 3.9: Output of polyplot.py

    3.6.2 Polynomials

    A polynomial is a mathematical expression involving a sum of powers in oneor more variables multiplied by coe�cients. A polynomial in one variable withconstant coe�cients is given by

    anxn + ... + a2x2 + a1x + a0 (3.6)

    One dimensional polynomials can be explored using the poly1d function ofnumpy. You can de�ne a polynomial by supplying the coe�cient as a list. Forexample , the statement p = poly1d([3,4,7]) constructs the polynomial 3x2+4x+7. The software supports algebraic operations on the polynomial. The followingexample describe addition, multiplication, division and di�erentiation.

    Example poly.py

    from pylab import *

    a = poly1d([3,4,5])

    b = poly1d([6,7])

    c = a * b + 5

    d = c/a

    print a

    print b

    print a * b

    print d[0], d[1]

    print a.deriv()

    print a.integ()

    The output of poly.py will look like;

  • CHAPTER 3. MATHEMATICS WITH PYTHON 41

    3x2 + 4x + 56x + 718x3 + 45x2 + 58x + 356x + 756x + 41x3 + 2x2 + 5xThe lines 4 and 5 shows the result of the polynomial division, quotient and

    reminder. Note that a polynomial can take an array argument for evaluationto return the results in an array. 2 The program polyplot.py evaluates thepolynomial

    x − x3

    6+

    x5

    120− x

    7

    5040(3.7)

    and the result is shown in �gure 3.9. Does it resemble a sinewave ? Theequation 3.7 is the �rst four terms of series representing sine wave. For thislimited number of terms, the result will match only for the given range of theparameter,−πtoπ.

    Exercise : Try increasing the range to see the mismatch. As you add morenumber of terms, the result will improve. Plot simple polinomials.

    Example polyplot.py

    from pylab import *

    x = linspace(-pi, pi, 100)

    a = poly1d([-1.0/5040,0,1.0/120,0,-1.0/6,0,1,0])

    y = a(x)

    plot(x,y)

    show()

    3.7 Matrix Operations

    We have learned how to create arrays using numpy in section 3.1. In this section,we will learn a little bit more about matrix operations that can be done usingnumpy. The numpy functions (some are already introduced in section 3.1)thatwill be discussed in this section are brie�y explained below. For more detailsrefer to [6, 7] on the Internet.

    3.7.1 array(list)

    Creates an array. Argument is a simple or nested list depending on the dimen-sions of the array to be created.

    a= array( [ [1,2], [3,4] ]) creates a 2 x 2 array

    2To know more type help(poly1d) at the python prompt after importing scipy;

    > > >import numpy

    > > >help(numpy.poly1d)

  • CHAPTER 3. MATHEMATICS WITH PYTHON 42

    3.7.2 arange(start, stop, step, dtype = None)

    Creates an evenly spaced one-dimensional array. Start, stop, stepsize anddatatype are the arguments. If datatype is not given, it is deduced from theother arguments.

    arange(2.0, 3.0, .1) is equivalent to array([ 2. , 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7,2.8, 2.9])

    3.7.3 linspace(start, stop, number of samples)

    Simila to arange(). Start, stop and number of samples are the arguments.linspace(1, 2, 11) is equivalent to array([ 1. , 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7,

    1.8, 1.9, 2. ])

    3.7.4 zeros(shape, datatype)

    Returns a new array of given shape and type, �lled zeros. The arguments areshape and datatype. For example zeros( [3,2], '�oat') generates a 3 x 2 array�lled with zeros as shown below.

    0.0 0.0 0.00.0 0.0 0.0

    3.7.5 ones(shape, datatype)

    Similar to zeros() except that tha values are initialized to 1.

    3.7.6 random.random_sample(shape)

    Similar to the functions above, but the matrix is �lled with random numbers of�oat type. For example, random.random_sample([3,3]) gave

    array([[ 0.3759652 , 0.58443562, 0.41632997],

    [ 0.88497654, 0.79518478, 0.60402514],

    [ 0.65468458, 0.05818105, 0.55621826]])

    3.7.7 reshape(array, newshape)

    Changes the shape of the array. The total number of ele,ents must be preserved.Working of reshape can be understood by looking at reshape.py and its result.

    Example reshape.py

    from numpy import *

    a = arange(20)

    b = reshape(a, [4,5])

    print b

    The result is shown below.

  • CHAPTER 3. MATHEMATICS WITH PYTHON 43

    array([[ 0, 1, 2, 3, 4],

    [ 5, 6, 7, 8, 9],

    [10, 11, 12, 13, 14],

    [15, 16, 17, 18, 19]])

    3.7.8 Arithmetic Operations

    Arithmetic operations performed on an array is carried out on all individualelements. Adding or multiplying an array object with a number will multiply allthe elements by that number. However, adding or multiplying two arrays havingidentical shapes will result in performing that operation with the correspondingelements. To clarify the idea, have a look at oper.py and its results.

    Example oper.py

    from numpy import *

    a = array([[2,3], [4,5]])

    b = array([[1,2], [3,0]])

    print a + b

    print a * b

    The output will be as shown below

    array([[3, 5],

    [7, 5]])

    array([[ 2, 6],

    [12, 0]])

    Modifying this program for more operations is left as an exercise to the reader.

    3.7.9 cross(array1, array2)

    Returns the cross product of two vectors, de�ned by

    A×B =

    ∣∣∣∣∣∣i j k

    A1 A2 A3B1 B2 B3

    ∣∣∣∣∣∣ = i(A2B3−A3B2)+j(A1B3−A3B1)+k(A1B2−A2B1)(3.8)

    For example the program cross.py gives an output of [-3, 6, -3]

    Example cross.py

    from numpy import *

    a = array([1,2,3])

    b = array([4,5,6])

    c = cross(a,b)

    print c

  • CHAPTER 3. MATHEMATICS WITH PYTHON 44

    3.7.10 dot(array1, array2)

    Returns the dot product of two vectors de�ned by A.B = A1B1 +A2B2 +A3B3. If you change the fourth line of cross.py to c=dot(a,b), the result will be 32.

    3.7.11 array.to�le(�lename), array = from�le(�lename)

    An array can be saved to text �le using to�le() and it can be read back usingfrom�le() methods, as shown by the code �leio.py

    Example �leio.py

    from numpy import *

    a = arange(10)

    a.tofile('myfile.dat')

    b = fromfile('myfile.dat')

    print b

    3.7.12 linalg.inv(array)

    Computes the inverse of a square matrix, if it exists. We can verify the resultby multiplying the original matrix with the inverse. Giving a singular matrixas the argument should normally result in an error message. In some cases, youmay get a result whose elements are having very high values (of the order of1014 or 1014) and it indicates an error.

    Example inv.py

    from numpy import *

    a = array([ [4,1,-2], [2,-3,3], [-6,-2,1] ], dtype='float')

    ainv = linalg.inv(a)

    print ainv

    print dot(a,ainv)

    Result of this program is printed below.

    [[ 0.08333333 0.08333333 -0.08333333]

    [-0.55555556 -0.22222222 -0.44444444]

    [-0.61111111 0.05555556 -0.38888889]]

    [[ 1.00000000e+00 -1.38777878e-17 0.00000000e+00]

    [-1.11022302e-16 1.00000000e+00 0.00000000e+00]

    [ 0.00000000e+00 2.08166817e-17 1.00000000e+00]]

    3.8 Equation solving using matrices

    Nonhomogeneous matrix equations of the form Ax = b can be solved by takingthe matrix inverse to obtain x = A−1b . The matrix we have chosen in theprevious example is the coe�cient matrix of the system of equations

  • CHAPTER 3. MATHEMATICS WITH PYTHON 45

    4x + y − 2z = 02x − 3y + 3z = 9−6x − 2y + z = 0

    can be represented in the matrix form as

    4 1 −22 −3 3−6 −2 1

    xyz

    = 09

    0

    and can be solved by �nding the inverse of the coe�cient matrix. xy

    z

    = 4 1 −22 −3 3

    −6 −2 1

    −1 090

    Using numpy we can solve this by adding the following two lines to inv.py

    b=array([0.0,9.0,0.0])

    print dot(ainv, b)

    The result will be [ 0.75 -2. 0.5 ], that means x = 0.75, y = −2, z = 0.5 . Thiscan be veri�ed by substituting them back in to the equations.

    Exercise: solve x+y+3z = 6; 2x+3y-4z=6;3x+2y+7z=0

    3.9 Numerical Di�erentiation

    The mathematical de�nition of the derivative of a function f(x) at point x isto take a limit as 4x goes to zero of the following expression:

    f(x + 4x2 ) − f(x −4x2 )

    4x

    The accuracy of the above equation depends on the stepsize 4x. Higherorder terms need to be included for better accuracy, that are neglected here sinceour objective is to just demonstrate the method. The program di�.py calculatesthe derivative of the function y = x3for any given value of x. The stepsize 4xcan be optionally speci�ed while calling the function deriv(). Di�erentiatingx3gives 3x2and for x = 2 , the result should be 12.0 but there will be someerror. The error decreases as you decrease 4x but beyond certain optimumvalue the error again increases.

    Example di�.py

  • CHAPTER 3. MATHEMATICS WITH PYTHON 46

    �8�6�4�2 0 2 4 6 8�1.0�0.50.0

    0.5

    1.0

    �8�6�4�2 0 2 4 6 8�1.0�0.50.0

    0.5

    1.0

    Figure 3.10: Outputs of vdi�.py (a)for 4x = 0.005 (b) for 4x = 1.0

    def f(x):

    return x**3

    def deriv(x,dx=0.005):

    df = f(x+dx/2)-f(x-dx/2)

    return df/dx

    print deriv(2.0)

    print deriv(2.0, 0.1)

    print deriv(2.0, 0.0001)

    The program prints the output:12.0000062512.002512.0000000025It can be seen that by increasing the stepsize from the default 0.005 to 0.1

    increased the error. Error reduced further for 4x = 0.0001 . Try smaller valuesand explore what happens. Also try this for other function like trigonometric,logarithmic etc.

    3.9.1 Vectorizing user de�ned functions

    The program di�.py in the previous example can only calculate the value of thederivative at a given point. We have already seen that the functions like sin(),cos() etc. implemented in numpy can take arrays as arguments and return theresults in an array, they are called vectorized functions. Fortunately numpy alsohas a function to to vectorize user de�ned functions. In the program vdi�.py ,we use this feature to get a vectorized version of our deriv() function. Thede�ned function is sine and the derivative is calculated using the vectorizedversion of deriv(). The actual cosine function also is plotted for comparison.The output of vdi�.py is shown in 3.10(a). The value of 4x is increased to 1.0by changing one line of code to y = vecderiv(x, 1.0) and the result is shownin 3.10(b). The values calculated using our function is shown using +marker,while the continuous curve is the expected result , ie the cosine curve.

  • CHAPTER 3. MATHEMATICS WITH PYTHON 47

    Figure 3.11: Trapezoid method. Area under the curve can be found by dividingit in to a large number of trapezoids.

    Example vdi�.py

    from pylab import *

    def f(x):

    return sin(x)

    def deriv(x,dx=0.005):

    df = f(x+dx/2)-f(x-dx/2)

    return df/dx

    vecderiv = vectorize(deriv)

    x = linspace(-2*pi, 2*pi, 200)

    y = vecderiv(x)

    plot(x,y,'+')

    plot(x,cos(x))

    show()

    3.10 Numerical Integration

    Numerical integration constitutes a broad family of algorithms for calculatingthe numerical value of a de�nite integral. The objective is to �nd the area underthe curve as shown in �gure 3.11. One method is to divide the are in to largenumber of trapezia and �nd the sum of their areas. Suppose we wish to �nd anapproximate value for ∫ x2

    x1

    f(x)

    The interval x1 ≤ x ≤ x2 is divided in to n sub-intervals, each of lengthh = (x2 − x1)/n, and the integral is approximated by

    I =h

    2

    (f(x1) + 2

    i=n−1∑i=1

    f(xi) + f(xn)

    )(3.9)

  • CHAPTER 3. MATHEMATICS WITH PYTHON 48

    This is the sum of the areas of the individual trapezia. The error in using thetrapezium rule is approximately proportional to 1/n2, so that if the number ofsub-intervals is doubled, the error is reduced by a factor of 4. The programtrapez.py does integration of a given function using equation 3.9. The last lineshows, how it can go wrong if the arguments are given in the integer format. It isleft as an exercise to the reader to modify the code to accept integer argumentsalso.

    Example trapez.py

    from math import *

    def sqr(a):

    return a**2

    def trapez(f, a, b, n):

    h = (b-a) / n

    sum = f(a)

    for i in range (1,n):

    sum = sum + 2 * f(a + h * i)

    sum = sum + f(b)

    return 0.5 * h * sum

    print trapez(sin,0.,pi,100)

    print trapez(sqr,0.,2.,100)

    print trapez(sqr,0,2,100) # Why the error ?

    3.11 Ordinary Di�erential Equations

    Di�erential equations are one of the most important mathematical tools usedin producing models for physical and biological processes. In this section, weconsider numerical methods for solving the initial value problem for �rst-orderordinary di�erential equations. By an initial value problem for �rst-order ordi-nary di�erential equations, we refer to the problem of the form:

    dy

    dx= f(x, y); y(x0) = y0

    The derivative of the function f(x) is known. The value of the function atsome value of x = x0 also is known. The objective is to �nd out the value of thefunction for other values of x. The underlying idea of any routine for solvingthe initial value problem is to rewrite the dy's and dx's as �nite steps 4y and4x, and multiply the equations by 4x. This gives algebraic formulas for thechange in the value of y(x) when x is changed by one stepsize 4x . In thelimit of making the stepsize very small, a good approximation to the underlyingdi�erential equation is achieved. Implementation of this procedure results in theEuler's method, which is conceptually very important, but not recommended forany practical use. In this section we will discuss Euler's method and the Runge-Kutta method with the help of example programs. For detailed informationrefer to [10, 11].

  • CHAPTER 3. MATHEMATICS WITH PYTHON 49

    3.11.1 Euler method

    The equations of Euler's method can be obtained as follows. By the de�nitionof derivative,

    y′(xn) =

    lim

    x → 0y(xn + h) − y(xn)

    h=⇒ y(xn + h) = y(xn) + hy

    ′(xn) (3.10)

    The above equations implies that, if the value of the function y(x) is knownto be yn at the point xn, its value at a nearby point xn+1 is given by yn +y

    ′(xn+1 −xn). The program euler.py calculates the value of sine function using

    its derivative, ie. the cosine function. We start from x = 0 , where sin(x) = 0and compute the subsequent values using the derivative, cos(x), and comparethe result with the actual sine function.

    Example euler.py

    import math

    h = 0.01 # stepsize

    x = 0.0 # initail value of x

    y = 0.0 # and the function, sin(x)

    while x < math.pi:

    print x, y, math.sin(x)

    y = y + h * math.cos(x) # Euler method

    x = x + h

    The output of euler.py can be redirected to a �le and ploted using xmgrace,using the commands

    # python euler.py > euler.dat

    # xmgrace -nxy euler.dat

    3.11.2 Runge-Kutta method

    The formula 3.10 used by Euler method which advances a solution from xntoxn+1is not symmetric, it advances the solution through an interval h, but uses deriva-tive information only at the beginning of that interval. Better results are ob-tained if we take trial step to the midpoint of the interval and use the valueof both x and y at that midpoint to compute the real step across the wholeinterval. This is called the second-order Runge-Kutta or the midpoint method.This procedure can be further extended to higher orders.

    The fourth order Runge-Kutta method is the most popular one and is com-monly referred as the Runge-Kutta method. In each step the derivative isevaluated four times as shown in �gure 3.12. Once at the initial point, twiceat trial midpoints, and once at a trial endpoint. Every trial evaluation uses thevalue of the function from the previous trial point, ie. k2 is evaluated using k1and not using yn. From these derivatives the �nal function value is calculated,The calculation is done using the equations,

  • CHAPTER 3. MATHEMATICS WITH PYTHON 50

    Figure 3.12: Fourth order Runge-Kutta method; for each step the function isevaluated at four points.

    k1 = hf(xn, yn)

    k2 = hf(xn +h

    2, yn +

    k12

    )

    k3 = hf(xn +h

    2, yn +

    k22

    )

    k4 = hf(xn + h, yn + k3)

    yn+1 = yn +16

    (k1 + 2k2 + 2k3 + k4) (3.11)

    The program rk4.py listed below uses the equations shown above to calculatethe sine function.

    Example rk4.py

    import math

    def rk4(x, y, yprime, dx = 0.01): # x, y , derivative, stepsize

    k1 = dx * yprime(x)

    k2 = dx * yprime(x + dx/2.0)

    k3 = dx * yprime(x + dx/2.0)

    k4 = dx * yprime(x + dx)

    return y + ( k1/6 + k2/3 + k3/3 + k4/6 )

    h = 0.01 # stepsize

    x = 0.0 # initail values

    y = 0.0

  • CHAPTER 3. MATHEMATICS WITH PYTHON 51

    while x < math.pi:

    print x, y, math.sin(x)

    y = rk4(x,y,math.cos) # Runge-Kutta method

    x = x + h

    The accuracy of RK method is far superior to that of Euler's method, for thesame step size. This is demonstrated by calculating the same function usingboth the methods and comparing the error with the actual sine function, usingthe program compareEuRK4.py.

    Example compareEuRK4.py

    import math

    def rk4(x, y, yprime, dx = 0.01):

    k1 = dx * yprime(x)

    k2 = dx * yprime(x + dx/2.0)

    k3 = dx * yprime(x + dx/2.0)

    k4 = dx * yprime(x + dx)

    return y + ( k1/6 + k2/3 + k3/3 + k4/6 )

    h = 0.01 # stepsize

    x = 0.0 # initail values

    y = 0.0 # for Euler

    z = 0.0 # for RK4

    while x < math.pi:

    print x, y - math.sin(x), z - math.sin(x) # errors

    y = y + h * math.cos(x) # Euler method

    z = rk4(x,z,math.cos,h) # Runge-Kutta method

    x = x + h

    3.12 Fractals

    Fractals are a part of fractal geometry, which is a branch of mathematics con-cerned with irregular patterns made of parts that are in some way similar to thewhole (e.g.: twigs and tree branches). A fractal is a design of in�nite details. Itis created using a mathematical formula. No matter how closely you look at afractal, it never loses it detail. It is in�nitely detailed, yet it can be contained ina �nite space. Fractals are generally self-similar and independent of scale. Thetheory of fractals was developed from Benoit Mandelbrot's study of complexityand chaos. Complex numbers are required to compute the Mandelbrot and Ju-lia Set fractals and it is assumed that the reader is familiar with the basics ofcomplex numbers.

    To compute the basic Mandelbrot (or Julia) set one uses the equation f(z) →z2 + c , where both z and c are complex numbers. The function is evaluated inan iterative manner, ie. the result is assigned to z and the process is repeated.The purpose of the iteration is to determine the behaviour of the values that areput into the function. If the value of the function goes to in�nity (practically

  • CHAPTER 3. MATHEMATICS WITH PYTHON 52

    0 50 100 150

    0

    50

    100

    150

    Figure 3.13: Output of julia.py

    to some �xed value, like 1 or 2) after few iterations for a particular value of z ,that point is considered to be outside the Set. A Julia set can be de�ned as theset of all the complex numbers (z) such that the iteration of f(z) → z2 + c isbounded for a particular value of c.

    To generate the fractal the number of iterations required to diverge is calcu-lated for a set of points in the selected region in the complex plane. The numberof iterations taken for diverging decides the color of each point. The points thatdid not diverge, belonging to the set, are plotted with the same color. Theprogram julia.py generates a fractal using a julia set. The program creates a2D array (200 x 200 elements). For our calculations, this array represents arectangular region on the complex plane centered at the origin whose lower leftcorner is (-1,-j) and the upper right corner is (1+j). For 200x200 equidistantpoints in this plane the number of iterations are calculated and that value isgiven to the corresponding element of the 2D matrix. The plotting is taken careby the imshow function. The output is shown in �gure 3.13. Change the valueof c and run the program to generate more patterns. The equation also may bechanged.

    �'

    Region of a complex plane ranging from -1 to +1 in both real

    and imaginary axes is rpresented using a 2D matrix

    having X x Y elements.For X and Y equal to 200,the stepsize

    in the complex plane is 2.0/200 = 0.01.

    The nature of the pattern depends much on the value of c.

    �'

    from pylab import *

    X = 200

    Y = 200

    MAXIT = 100

    MAXABS = 2.0

    c = 0.02 - 0.8j # The constant in equation z**2 + c

    m = zeros([X,Y],dtype=uint8) # A two dimensional array

  • CHAPTER 3. MATHEMATICS WITH PYTHON 53

    def numit(x,y): # number of iterations to diverge

    z = complex(x,y)

    for k in range(MAXIT):

    if abs(z)

  • Bibliography

    [1] http://matplotlib.sourceforge.net/users/pyplot_tutorial.html

    [2] http://en.wikipedia.org/wiki/List_of_curves

    [3] http://www.gap-system.org/~history/Curves/Curves.html

    [4] http://www.gap-system.org/~history/Curves/Ellipse.html

    [5] http://mathworld.wolfram.com/

    [6] http://www.scipy.org/Numpy_Example_List

    [7] http://docs.scipy.org/doc/

    [8] http://numericalmethods.eng.usf.edu/mws/gen/07int/index.html

    [9] http://www.angel�re.com/art2/fractals/lesson2.htm

    [10] http://www.�zyka.umk.pl/nrbook/bookcpdf.html

    [11] http://www.mathcs.emory.edu/ccs/ccs315/ccs315/ccs315.html

    54