Experiment No2 : Familiarization of Scientific Computing

 Objective

  • To understand about Functions in Python with examples

  • Basic arithmetic functions such as abs, sine, real, imag, complex, sinc etc. using built in modules.

  • Vectorized computing without loops for fast scientific applications.

Theory

Functions in Python

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.

Defining a Function

  • You can define functions to provide the required functionality. Here are simple rules to define a function in Python.

  • Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).

  • Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.

  • The first statement of a function can be an optional statement - the documentation string of the function or docstring.

  • The code block within every function starts with a colon (:) and is indented.

  • The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

Syntax

def functionname( parameters ):

   "function_docstring"

   function_suite

   return [expression]

Calling a Function

Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.

Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is the example to call printme() function −

Example 1

Creating a function named printme

def printme( str ):

   print (str)

   return;

calling the function printme

printme("Manu Prasad")

Output

Manu Prasad

Example 2

Creating a function named printme

def my_funct(fname,lname):

  print(fname+" "+lname)


calling the function printme

my_funct("Manu","Prasad")

Output

Manu Prasad

 

abs() in Python

The abs() function is used to return the absolute value of a number.

Syntax:

abs(number)

number : Can be integer, a floating point

number or a complex number

The abs() takes only one argument, a number whose absolute value is to be returned. The argument can be an integer, a floating point number or a complex number.

If the argument is an integer or floating point number, abs() returns the absolute value in integer or float. In case of complex numbers, abs() returns only the magnitude part and that can also be a floating point number.

Example Program

# floating point number 

float = -54.26

print('Absolute value of float is:', abs(float)) 

# An integer 

int = -94

print('Absolute value of integer is:', abs(int)) 

# A complex number 

complex = (3 - 4j

print('Absolute value or Magnitude of complex is:', abs(complex)) 

 

Output

Absolute value of float is: 54.26

Absolute value of integer is: 94

Absolute value or Magnitude of complex is: 5.0

Sine in Python

Python has also a built-in module called math, which extends the list of mathematical functions.

To use it, you must import the math module:

import math

When you have imported the math module, you can start using methods and constants of the module.

Program 1

# Import math Library

import math

# Return the sine of different values

print (math.sin(0.00))

print (math.sin(-1.23))

print (math.sin(10))

print (math.sin(math.pi))

print (math.sin(math.pi/2))


Output

0.0

-0.9424888019316975

-0.5440211108893698

1.2246467991473532e-16

1.0


Some other Math methods

Sr.No

Function & Returns ( description )

1

abs(x)

The absolute value of x: the (positive) distance between x and zero.

2

ceil(x)

The ceiling of x: the smallest integer not less than x

3

cmp(x, y)

-1 if x < y, 0 if x == y, or 1 if x > y

4

exp(x)

The exponential of x: ex

5

fabs(x)

The absolute value of x.

6

floor(x)

The floor of x: the largest integer not greater than x

7

log(x)

The natural logarithm of x, for x> 0

8

log10(x)

The base-10 logarithm of x for x> 0.

9

max(x1, x2,...)

The largest of its arguments: the value closest to positive infinity

10

min(x1, x2,...)

The smallest of its arguments: the value closest to negative infinity

11

modf(x)

The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float.

12

pow(x, y)

The value of x**y.

13

round(x [,n])

x rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.

14

sqrt(x)

The square root of x for x > 0


Program

x = 3+5j

print(type(x))

print(x.real)

print(x.imag)

Output

<class 'complex'>

3.0

5.0

Vectorization in Python

Vectorization is used to speed up the Python code without using loop. Using such a function can help in minimizing the running time of code efficiently. Various operations are being performed over vector such as dot product of vectors which is also known as scalar product as it produces single output, outer products which results in square matrix of dimension equal to length X length of the vectors, Element wise multiplication which products the element of same indexes and dimension of the matrix remain unchanged.

Dot Product:

Dot product is an algebraic operation in which two equal length vectors are being multiplied such that it produces a single number. Dot Product is often called an inner product. This product results in a scalar number. Let’s consider two matrices a and b of same length, the dot product is done by taking the transpose of first matrix and then mathematical matrix multiplication of a’(transpose of a) and b is followed as shown in the figure below.

Let's compare two types of coding methods in python

Programe


# Dot product 

import time 

import numpy 

import array 

  

a = array.array('i'

for i in range(200): 

    a.append(i); 

  

b = array.array('i'

for i in range(200, 400): 

    b.append(i) 

  

# classic dot product of vectors implementation  

tic = time.process_time() 

dot = 0.0

  

for i in range(len(a)): 

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

  

toc = time.process_time() 

  

print("dot_product = "+ str(dot)); 

print("Computation time = " + str(1000*(toc - tic )) + "ms"

   

  

n_tic = time.process_time() 

n_dot_product = numpy.dot(a, b) 

n_toc = time.process_time() 

  

print("\nn_dot_product = "+str(n_dot_product)) 

print("Computation time = "+str(1000*(n_toc - n_tic ))+"ms"


Output

dot_product = 6626700.0

Computation time = 0.100817999999947ms


n_dot_product = 6626700

Computation time = 0.12626199999976606ms

Element wise Product:

Element-wise multiplication of two matrices is the algebraic operation in which each element of the first matrix is multiplied by its corresponding element in the later matrix. Dimension of the matrices should be the same. Consider two matrices a and b, index of an element in a is i and j then a(i, j) is multiplied with b(i, j) respectively as shown in the figure below.

Pictorial representation of Element wise product –




Program

# Element-wise multiplication 

import time 

import numpy 

import array 

  

a = array.array('i'

for i in range(50000): 

    a.append(i); 

  

b = array.array('i'

for i in range(50000, 100000): 

    b.append(i) 

  

# classic element wise product of vectors implementation  

vector = numpy.zeros((50000)) 

  

tic = time.process_time() 

  

for i in range(len(a)): 

      vector[i]= a[i]*b[i] 

  

toc = time.process_time() 

  

print("Element wise Product = "+ str(vector)); 

print("\nComputation time = "+str(1000*(toc - tic ))+"ms"

  

n_tic = time.process_time() 

vector = numpy.multiply(a, b) 

n_toc = time.process_time() 

 

print("Element wise Product = "+str(vector)); 

print("\nComputation time = "+str(1000*(n_toc - n_tic ))+"ms"


Output

Element wise Product = [0.00000000e+00 5.00010000e+04 1.00004000e+05 ... 4.99955001e+09

 4.99970000e+09 4.99985000e+09]


Computation time = 14.302591000000309ms

Element wise Product = [        0     50001    100004 ... 704582713 704732708 704882705]


Computation time = 0.9973990000000654ms


Inference

Familiarized and understood Python based scientific computing and its basics 


No comments:

Post a Comment

Signals & System Lect 15 | Stable & Unstable Systems | Solved examples

  ECT 204 SIGNALS AND SYSTEMS Topics covered  00:00 - Introduction to Stable & unstable Systems 01:08 - BIBO criteria 03:38 Problem No 1...