Skip to main content

Functions in Python

Functions in Python


What You will Learn

  • You will learn the syntax of Python functions
  • You will learn to import the functions to other codes

The Syntax

The syntax used the keyword $def$ followed the name of the function again followed by a colon (:) that is then followed by an indented code block of instructions. The function

def function_name(arg1.arg2,....argN):

statements

return results

A Simple Python Function

Needless to say that the statements and the return command should form an indented block. Consider a simple function that returns the sum of the input values. It is realized as the function below.
def summ(x,y):

return x+y

Unlike MATLAB or IDL, it is possible to execute a function in the Python shell. You may type the above function in a Python shell or an enhanced Python shell such as IPython. Once the function is executed, if you type summ(7,4), it returns 11. If you give summ(2+3*1j,4-2*1j), it returns 6+1j.

Python Function for Fibonacci Series

The following Python function returns the first $N$ Fibonacci numbers.
from scipy import *
def fibonacci(n):

y=[1,1]

for i in range(2,n):

t=y[i-1]+y[i-2]

y.append(t)

return y

The first line in the series initiates a blank array $w$. The second lines loads the first two values of the sequence. The remaining values are computed and appended to the blank array using the iterative steps in the for loop.

Importing the above Function to Compute the Golden Ratio

You can compute the golden ratio which is the ratio of successive terms in a Fibonacci series. The golden ratio is approximately $\frac{1+\sqrt{5}}{2}$. The above function, stored as fibonacci.py in the same directory can be imported and used for computing the golden ratio, as shown in the code below. The variable x contains the first 100 Fibonacci numbers. The ratio of each term with the previous term is computed and these 99 values are plotted as shown in the figure below.
from scipy import *
from pylab import *
from fibonacci import *
N=100
x=fibonacci(100)
y=[]
for i in range(1,N):

y.append(x[i]*((x[i-1])**-1))
plot(range(0,N-1),y)
xlabel("iterations")
ylabel("Golden ratio")
grid('on')
show()

It is observed that the ratio converges to $\frac{1+\sqrt{5}}{2}$ fairly quickly.

Function to Compute $\pi$

Now that you understood the function for Fibonacci numbers, let us look at a function that returns the approximate value of $\pi$, based on the construction in the figure below. The circle of unit radius is circumscribed by the square.

$\text{The probability that a point lies within the circle}=p=\frac{\text{Area of circle}}{\text{Area of square}}=\frac{\pi\times 1^{2}}{2^{2}}=\frac{\pi}{4}\\ =\frac{\text{No. of points within circle}}{\text{No. of points within square}}$,

So, $\pi=4p$.

The number of points can be calculated by constructing a closely spaced square grid of side 2 units, as in the code below.

from scipy import *
from pylab import *
def pival(N):

x=r_[-1:1:N**-1]

y=r_[-1:1:N**-1]

despoints=[]

for i in x:

for j in y:

if sqrt(i**2+j**2)<=1:

despoints.append(sqrt(i**2+j**2))

pival=4*len(despoints)*((len(x)*len(y))**-1)

return pival
Two vectors x and y each of length N create a rectangular grid with total number of points being $len(x)\times len(y)$. The desired points within the unit circle (i.e. all values below $\sqrt{i^{2}+j^{2}}$) are stored in the array $despoints$. The probability of a point being within the unit circle is computed by dividing the number of points in $despoints$ by the total number of points which when multiplied by 4 gives the approximate value of $\pi$. Run this code to generate the corresponding Python byte code. This module can be imported as shown below. it returns the value $3.141529$.
from scipy import *
from pival import *
print pival(1000)

What You Learned

  • You understood the syntax and use of Python functions with two examples
  • You imported the functions into other codes.

Comments

Popular posts from this blog

Overview of Scientific Computing

Introduction Scientific computing broadly means computations carried out for scientific or engineering needs. This mostly includes processing of large arrays or matrices, plotting of functions, solving equations, performing mathematical transforms etc very fast while keeping programming hassles at a minimum. Requirements of Scientific Computing The language for scientific computing should be Interpreted should be modular should have easy routines for array, matrix and vectors should have a publication quality plotting library Python for Scientific Computing Python is an interpreted, modular language that is suitable for scientific computing. Modules such as numpy, scipy etc provide many scientific computing tools. The module matpplotlib alias pylab provides publication quality plotting libraries. Python 2.7 and Python 3 are available in all major Linux distros and can be installed as bundle such as anaconda in Windows. An enhanced Python shell ipython...

Matrix Operations using Python

Dr. Hari V S Department of Electronics and Communication College of Engineering Chengannur What You will Learn You will learn to create matrices You will learn to solve linear equations by computing the inverse of a matrix. You will learn to compute the eigen values of a matrix Matrices using Python A $5\times 3$ matrix is created, printed and displayed as an image using the code below. Its transpose is generated by the $transpose()$ function. from scipy import * from pylab import * x=mat([[1,2,3,4,5],[4,5,6,9,15],[7,8,9,23,25]]) print x print shape(x) print transpose(x) matshow(x) show() Solution of Linear Equations Linear systems are represented by matrix equations. See the electrical network in the figure below. All resistances are in $\Omega$. The network is described by the set of equations. \begin{equation} 9I_{1}-4 I_{2}=20 \end{equation} \begin{equation} -4I_{1}-6 I_{2}=-10 \end{equation} \begin{equation} 8I_{3}-3 I_{4}=-20 \end...

Lists, Arrays and Matrices and their Visualization

What You Will Learn You will create lists, arrays and matrices using scipy You will learn to slice, reverse, append and plot arrays Lists in Python Type in the code at the Ipython console from scipy import * x=[1,2,3,4,5] The first line imports all modules in scipy. The second line creates a list in the variable x. Type x at the console and observe the list Type x[0:2] at the console and observe the first two values in the list Type x[3:5] at the console and observe a slice of the list Type x[::-1] at the console and observe the reversed list Type len(x) at the console and observe the length of the list x Type y=[4,5,6] and then type x+y observe the two lists getting concatenated. Type append(x,y) observe a similar result Type z=['apple','orange','pear'] to create a list of strings Arrays using Scipy scipy and numpy provide arrays that support mathematical operations. Type x=array([1,2,3,4,5]) at the cons...