Sunday, January 26, 2014

PARALLEL PROGRAMMING PARADIGMS


In this blog we shall provide a soft introduction into parallel programming using MPI framework. Beginning with concepts of a parallel machine and models of parallel computation, we will introduce MPI basics in section 2. Section 3 will contain a small hands on tutorial and a summary shall be provided in section 5 along with what to expect in next post.

Introduction

Von Nuemann Model: Single Machine Model consisting of a CPU connected to memory. The CPU executes the program specifying sequqence of read write operations of memmory.
Multicomputer Model : Several Von Neumann machines linked via interconnection network. The individual machines execute their own program and uses local memmory, but also exchange messages through network.
Role of message passing:
  1. Communicate with other processes.
  2. Read/Write remote memmory.

Examples of Parallel Computing Architecture:

  1. Distributed-memmory MIMD: The computer memmory is not placed at a central location but rather distributed amongst several processors. Each of these can execute a separate stream of instructions using local data.
    Difference wrt multicomputer model: message sending cost b/w two nodes may depend on location and traffic.
  2. Shared-memmory MIMD: Several processors share a centrally placed memmory through a bus or a hierarchy of them. Usually each processor is provided with a cache to temporarily store copies of frequenty used items, in order to reduce the calls to main memmory.
    This architecture is more close to multicomputers since shared memmory allows an easier paradigm for message passing.
  3. SIMP: Several processors execute single instruction stream on different peice of data. This is a simple approach but limited to a very narrow range of problems having a high degree of regularity.
  4. MPMD: This is an acronym for Multiple Program Multiple Data and differs from SIMP in respect that each processor executes different program.

The MPI Programming Model


The Message Passing Interface (MPI) is based on MPMD model and views a computation as comprising of one or more proesses that communicate via library routines. These processes are usually created at the initialization and may communicage one or more of following modes:
  1. Point-to-Point Communication.
  2. Collective Communication.
In both these modes we use a mechanism called communicator that for defining modules encapsulating internal communication standards.

The Basic Functions: Getting Started


Here we introduce six beginner's routines and few points to explain the basic functionality. Following function is called before any other MPI command in order to intialize the environment.
MPI_INIT 
   Role:       Start an MPI computation.
   Prototype:  int MPI_Init( int *argc, char ***argv )
   Prameters:  Two parameters
           argc: Pointer to the number of arguments
               argv: Pointer to the argument vector
  
During MPI_Init, all of MPI’s global and internal variables are constructed. Like construction of a communicator enveloping all of the processes spawned, assignment of unique rank to each.

After we are done with all the MPI stuff, MPI_Finalize is used to clean up the MPI environment. No more MPI calls can be made after this one.
MPI_FINALIZE
   Role:       Finish/Terminate an MPI computation.
   Prototype:  int MPI_Finalize( void )
   Parameters: None
   
Note: Both these functions must be called by a single and same thread namely the main thread. Although MPI standard is silent about what can be done before MPI_INIT and after MPI_FINALIZE but its better to do as little as possible and avoid any opeation that change external state of program like opening files, reading stdin or writing stdout.

Following function is used to find number of processes in a communicator:

MPI_COMM_SIZE
   Role:       Give size of group asstd. to a communicator.
   Prototype:  int MPI_Comm_Size( MPI_Comm comm, int *size)
   Prameters:  Two parameters
           comm: Input communicator to be probed.
               size: Carrier to contain the output.

Following would return the rank of calling process in that communicator
MPI_COMM_RANK
   Role:       Give rank of calling process in communicator.
   Prototype:  int MPI_Comm_rank( MPI_Comm comm, int *size)
   Prameters:  Two parameters
           comm: Input communicator to be probed.
               size: Carrier to contain the output.

Note: Both the above can be safely used by multiple threads and from within a signal handler.

Now we introduce two functions that form the backbone of message passing facility. Below is the MPI_Send function used to send a message to another process.
MPI_SEND 
   Role:       Perform a blocking send
   Prototype:  int MPI_Send(
                void *buf, 
                int count, 
                MPI_Datatype datatype, 
                int dest, 
                int tag,
                MPI_Comm comm
                );
     
   Prameters: Six parameters
              buf  : add of send buffer
              count: num of elems in send buffer
              dest : rank of destination
              tag  : message tag
              comm : communicator
    

Similarly, a message from a specific source can be received with following function:
MPI_RECV
   Role:       Perform a blocking recieve
   Prototype:  int MPI_Recv(
                void *buf, 
                int count, 
                MPI_Datatype datatype, 
                int source, 
                int tag,
                MPI_Comm comm,
                MPI_Status *status
               );
    

   Prameters: Seven parameters, two new ones.
              source: rank of source.
              status: status of recv buffer.
   

Note: The parameter datatype indicates the type of data which is being sent. For example, if you wish to send an int, the datatype MPI_Int must be used. A complete list of MPI datatypes can be found here.

Note: The count argument does not indicate the length of message but rather the MAXIMUM length of it.

Note: Both these routines may be used by multiple threads but they however are not interrupt safe.

Summary


We provided a very brief introduction into the subject of parallel computing in MPI paradigm. In addition to Von-Neumann's concept of a single machine we know about various paradigms for parallel processing. We also know how to initialize MPI computing environment and how to cleanup after use. We know how to find the total number of processes in a communicator as well as how to find the rank of current process. Finally we had a look into the MPI_Send and MPI_Recv functions which are used for point-to-point communication between two processes.

We know that much better clarity about these functions can be obtained by working out the actual examples. So we will present a basic hello world program and a simple message exchange program in next post along with the explanations.

Saturday, November 2, 2013

LOOPS AND SUBROUTINES IN ASSEMBLEY LANGUAGE

The LOOPS and SUBROUTINES are two of the most important constructs which are at the heart of all programming paradigms. The IBM's BAL (360) provides support for creating efficient LOOPS and SUBROUTINE calls with help of a rich inventory of the instructions at hand.

CREATING LOOP STRUCTURES

The LOOPS are essentially the chunks of code which are executed repeatedly subject to certain control condition. Two types of looping structures are most frequently encountered:
  • Type1: Loop with known number of cycles
  • Type2: Loop with unknown number of cycles
The Type 1 loops are often created either of following instructions:
         BCT    r1,D(X,B)
         BCTR   r1,r2
   

The effect of executing either of these is shown in following pseudocode:
BCT:
   |r1| = |r1|-1
   if(|r1|!=0) take branch to D(X,B)
   else go to next instruction
       1. Condition code remains unaltered.
BCTR:
   |r1| = |r1|-1
   if((|r1|!=0)&&(|r2|!=R0)) take branch to |r2|
   else go to next instruction.
       1. Condition code remains unaltered.

The type 2 loops are created using either of following:
         BXLE  r1,r2,D(B)
         BXH   r1,r2,D(B)
           1. Note the absence of X in address.
   


Both of these are examples of type RS instructions that are coded as follows.
   h_{0}h_{0}h_{r1}h_{r2}h_{b}h_{D}h_{D}h_{D}
   Where:
     h_{0}h_{0} : Machine code of the instruction
     h_{r1}: Register r1
     h_{r2}: Register r2
     h_{B} : Base Register
     h_{D} : 3 Byte displacement
   


Whenever either of these are present, following are assigned:
  • Index Register (INDR)
  • Increment Register (INCR)
  • Limit Register (LIMR)
This is done according to following pseudocode:
     INDR  = r1
     if (r2 == Even Numbered) :
           INCR = r2
           LIMR = r2+1
     else if (r2 == Odd Numbered):
           INCR = r2
           LIMR = r2
  

Once these three are identified, working of both these instructions can be understood below:
BXLE:
    |INDR| = |INDR|+|INCR|
    if (|INDR| <= |LIMR|) take a branch to D(B)
    else go to next instruction
        1. Condition code remains unaltered.
BXH:
   |INDR| = |INDR|+|INCR|
   if (|INDR| >  |LIMR|) take a branch to D(B)
   else go to next instruction
       1. Condition code remains unaltered.
  

CREATING INTERNAL SUBROUTINES

Succession of logical steps for calling a subroutine is summarised below:
   1. Store the address of next instruction in some register.
   2. Take a branch to the address where subroutine begins.
   3. Once there, store all the registers to an area in memmory
   4. Perform the tasks coded into the subroutine
   5. At the end, restore all registers from area in Step:3
   6. Take a branch to main program using information stored in Step:1 
  

The Steps 1,2 can be implemented using either of following instructions:
          BAL   r,D(X,B)
          BALR  r1,r2
Pseudocode:

BAL:
   |r| = |PSW (right 32 bits)|
   take a branch to D(X,B)

BALR:
  |r1| = |PSW (right 32 bits)|
  if (r2 != R0) take a branch to |r2|
  else go to next instruction 
  

The BAL instruction cause right 32 bits of PSW which contain the address of next instruction, to be stored in 'r' register. Then a branch is taken to the address D(X,B), which in current context is the address of subroutine we wish to call. The BALR instruction is similar to BAL, except that the branching takes place into the address contained in r2 and that if r2 is R0, branching does not take place.

Upon being called, a subroutine needs to store caller's data before using any of the registers, so that they may be restored upon exit. This constitute steps 3 and 5, and may be implemented with following instructions:

          STM   r1,r2,D(B)   :STORE TO MEMMORY
          LM    r1,r2,D(B)   :LOAD FROM MEMMORY

Pseudocode:

STM:
   Store registers r1 through r2 into 1 FW each
   of the contiguous memmory starting D(B). 

LM :
   Restore registers r1 through r2 from contiguous 
   memmory starting at D(B), reading 1 FW into each.
  
*NOTE: Note address is coded as D(B): X not allowed !!
  

Here we show a pseudocode to demonstrate the call to an internal subroutine:
***********************************************************
*MAIN FUNCTION: CALLER DEMO                               *
*R6: CONTAINS ADDRESS OF NEXT TO CALLER                   *
***********************************************************
MAIN     CSECT                   :CONTROL SECT
         USING MAIN,15           :ESTABLISH BASE REG
         BAL   R6,SUBR           :STORE NEXT INSTR,
*                                 AND BRANCH TO A(SUBR)
         BR    R14               :EXIT 
***********************************************************
*SUBROUTINE SUBR: DEMO SKELETON                           *
*R6: CONTAINS ADDRESS OF NEXT TO CALLER                   *
***********************************************************
SUBR     STM   R0,R15,SUBSAFE    :STORE REGS INTO MEMMORY
         ...   ..............    :DO STUFF
         ...   ..............    :DO STUFF
         LM    R0,R15,SUBSAFE    :RESTORE REFS FROM MEMMORY
         BR    R6                :BRANCH BACK TO CALLER
         LTORG                   :LITERALS STORAGE
SUBSAFE  DS   18F                :RESERVE REG STORAGE
         END   MAIN              :END MAIN
   

Its time to finish the current post here, please take time to post your comments or suggestions below. If you have any example code, feel free to share that as well.

Tuesday, October 15, 2013

A Dirty Introduction to MySQL

In course of metamorphosis from a Physicist into a Computer scientist, I am currently taking a course on Database design and management. An important component of DBMS is DQL (Data Querey Language), which help us to generate views (virtual tables) using data from inter-related base (physical) tables. Following summary is based on the notes taken inside one of the lectures taken recently: Consider a small relational database consisting of three relations: S, P and SP
The relation S
S# SNAME STATUS CITY
S1 Rick 30 Geneve
S2 Jeffrey 20 Paris
S3 Vitaliano 30 Roma
S4 Alexandre 10 Moscow
S5 Mehmet 10 Ankara
The relation P:
P# PNAME COLOR WEIGHT
P1 BOLT BLUE 12
P2 BOLT RED 17
P3 NUT GREEN 10
P4 SCREW GREEN 15
P5 CAM BLUE 12
P6 COG RED 10
The relation SP:
S# P# QTY
S1 P2 300
S2 P2 200
S2 P6 100
S3 P4 400
S3 P5 300
S3 P6 200
S4 P1 100
S4 P2 100
S1 P6 300
S5 P2 100
S5 P3 300
S5 P1 200



INTERACTIVE SQL QUERIES

Select one of the databases for use:
using database example;
Summary of all the tables in SP:
mysql> show tables;
+-------------------+
| Tables_in_example |
+-------------------+
| P                 |
| S                 |
| SP                |
+-------------------+
3 rows in set (0.00 sec)
Now let us try generating some views from data stored in database:
  1. Get Supplier Ids and Supplier Status for the ones in Paris
    mysql> SELECT * FROM S WHERE CITY="PARIS";
    +-----+-----------+--------+-------+
    | SID | SNAME     | STATUS | CITY  |
    +-----+-----------+--------+-------+
    | S2  | Jefferey  |     20 | Paris |
    | S4  | Alexandre |     10 | Paris |
    +-----+-----------+--------+-------+
    2 rows in set (0.01 sec)
    
  2. Get ParID for all the parts supplied:
    mysql> select PID from SP;
    +-----+
    | PID |
    +-----+
    | P2  |
    | P6  |
    | P2  |
    | P6  |
    | P4  |
    | P5  |
    | P6  |
    | P1  |
    | P2  |
    | P1  |
    | P2  |
    | P3  |
    +-----+
    12 rows in set (0.00 sec)
    
  3. Which parts have even been supplied?
    SELECT DISTINCT PID FROM SP;
    +-----+
    | PID |
    +-----+
    | P2  |
    | P6  |
    | P4  |
    | P5  |
    | P1  |
    | P3  |
    +-----+
    6 rows in set (0.00 sec)
    
  4. List details for all the suppliers:
    mysql> SELECT * FROM S;
    +-----+-----------+--------+--------+
    | SID | SNAME     | STATUS | CITY   |
    +-----+-----------+--------+--------+
    | S1  | Rick      |     30 | Geneve |
    | S2  | Jefferey  |     20 | Paris  |
    | S3  | Vitaliano |     30 | Roma   |
    | S4  | Alexandre |     10 | Paris  |
    | S5  | Tylan     |     10 | Ankara |
    +-----+-----------+--------+--------+
    5 rows in set (0.00 sec)
    
  5. Select supplier details from Paris whose status is greater than 10
    mysql> SELECT * FROM S WHERE STATUS>10 AND CITY="PARIS";
    +-----+----------+--------+-------+
    | SID | SNAME    | STATUS | CITY  |
    +-----+----------+--------+-------+
    | S2  | Jefferey |     20 | Paris |
    +-----+----------+--------+-------+
    1 row in set (0.00 sec)
    
  6. List all the suppliers who are not from Paris,
    mysql> select * from S where CITY<>"PARIS";
    +-----+-----------+--------+--------+
    | SID | SNAME     | STATUS | CITY   |
    +-----+-----------+--------+--------+
    | S1  | Rick      |     30 | Geneve |
    | S3  | Vitaliano |     30 | Roma   |
    | S5  | Tylan     |     10 | Ankara |
    +-----+-----------+--------+--------+
    3 rows in set (0.00 sec)
    
  7. List all suppliers not from Paris, in descending order
    mysql> SELECT * FROM S WHERE STATUS>10 
    AND CITY<>"PARIS" ORDER BY STATUS DESC; +-----+-----------+--------+--------+ | SID | SNAME | STATUS | CITY | +-----+-----------+--------+--------+ | S1 | Rick | 30 | Geneve | | S3 | Vitaliano | 30 | Roma | +-----+-----------+--------+--------+ 2 rows in set (0.00 sec)
  8. For each part get PartID and Cities supplying it
    mysql> select DISTINCT PID, CITY from SP,S 
    where SP.SID=S.SID order by PID; +-----+--------+ | PID | CITY | +-----+--------+ | P1 | Paris | | P1 | Ankara | | P2 | Paris | | P2 | Geneve | | P2 | Ankara | | P3 | Ankara | | P4 | Roma | | P5 | Roma | | P6 | Paris | | P6 | Roma | | P6 | Geneve | +-----+--------+ 11 rows in set (0.00 sec)
  9. Ex6: List the supplier numbers for all pairs of suppliers such that two suppliers are located in the same city.
    mysql> SELECT T1.SID, T2.SID FROM S AS T1, S AS T2 
    WHERE T1.CITY=T2.CITY AND T1.SI>T2.SID; +-----+-----+ | SID | SID | +-----+-----+ | S2 | S4 | +-----+-----+ 1 row in set (0.00 sec)
  10. List all the suppliers who have supplied P2:
    mysql> SELECT DISTINCT SNAME FROM S,SP 
    WHERE S.SID=SP.SID AND SP.PID="P2"; +-----------+ | SNAME | +-----------+ | Rick | | Jefferey | | Alexandre | | Tylan | +-----------+ 4 rows in set (0.00 sec)
  11. List the suppliers who have supplied RED colored parts:
    mysql> SELECT DISTINCT SNAME FROM S,P,SP 
    WHERE S.SID=SP.SID AND SP.PID=P.PID AND P.COLOR="RED"; +-----------+ | SNAME | +-----------+ | Rick | | Jefferey | | Vitaliano | | Alexandre | | Tylan | +-----------+ 5 rows in set (0.00 sec)
  12. List suppliers who have supplied P2 using IN command:
    mysql> SELECT SNAME FROM S WHERE 
    S.SID IN (SELECT DISTINCT SID FROM SP WHERE SP.PID="P2"); +-----------+ | SNAME | +-----------+ | Rick | | Jefferey | | Alexandre | | Tylan | +-----------+ 4 rows in set (0.00 sec)
  13. List the suppliers who have supplied RED colored parts using IN command:
    mysql> SELECT SNAME FROM S WHERE S.SID IN (SELECT DISTINCT 
    SP.SID FROM SP, P WHERE SP.PID=P.PID AND P.COLOR="RED"); +-----------+ | SNAME | +-----------+ | Rick | | Jefferey | | Vitaliano | | Alexandre | | Tylan | +-----------+ 5 rows in set (0.00 sec)
  14. List the supplier numbers for suppliers with status less than the current maximum status value in the S table
    mysql> SELECT SID FROM S WHERE STATUS 
    < ANY (SELECT STATUS FROM S); +-----+ | SID | +-----+ | S2 | | S4 | | S5 | +-----+ 3 rows in set (0.00 sec)
  15. For each Part, get the PID and the total number of suppliers supplying the part.
    mysql>  SELECT PID,COUNT(SID) AS NUMSPPLRS FROM SP GROUP BY PID ;
    
    +-----+-----------+
    | PID | NUMSPPLRS |
    +-----+-----------+
    | P1  |         2 |
    | P2  |         4 |
    | P3  |         1 |
    | P4  |         1 |
    | P5  |         1 |
    | P6  |         3 |
    +-----+-----------+
    6 rows in set (0.00 sec)
    
  16. List the part numbers for all parts supplied by more than one supplier.
    mysql> SELECT PID FROM SP GROUP BY SP.PID HAVING COUNT(*)>1;
    +-----+
    | PID |
    +-----+
    | P1  |
    | P2  |
    | P6  |
    +-----+
    3 rows in set (0.00 sec)
    
  17. List total number of currently registered suppliers,
    mysql> SELECT COUNT(*) FROM S ;
    +----------+
    | COUNT(*) |
    +----------+
    |        5 |
    +----------+
    1 row in set (0.00 sec)
    
  18. Count the number of suppliers, who have actually made a supply
    mysql> SELECT COUNT(SID) FROM
    (SELECT DISTINCT SID FROM SP ) AS A; +------------+ | COUNT(SID) | +------------+ | 5 | +------------+ 1 row in set (0.00 sec)
  19. Get the total quantity of part P2 being supplied
    mysql> SELECT SUM(QTY) FROM SP WHERE SP.PID="P2";
    +----------+
    | SUM(QTY) |
    +----------+
    |      700 |
    +----------+
    1 row in set (0.00 sec)
    
  20. List suppliers whose name starts with letter A
    mysql> SELECT * FROM S WHERE SNAME LIKE "A%";
    +-----+-----------+--------+-------+
    | SID | SNAME     | STATUS | CITY  |
    +-----+-----------+--------+-------+
    | S4  | Alexandre |     10 | Paris |
    +-----+-----------+--------+-------+
    1 row in set (0.00 sec)
    
In the next post I will post the notes for the lecture on Data Definition Language, so as to document the metamorphosis.

Monday, November 8, 2010


Contents

  1. Introduction
  2. Getting Started With C++
  3. Two Simple Problems
  4. Execution Control: if, but, and while
  5. Functions, Pointers and Arrays

Introduction

This tutorial has been designed to serve students and practising professionals in  science and engineering. The aim is to quickly enable the reader to write/read non trivial C++ applications without really bothering about the theoretical details of language and it's grammar. So we use a large number of examples as we proceed, in order to gently nail in the common features of the core language as well as the standard utility library. An Older Post

Getting Started With C++ 

Begin with what programmers usually call "Hello World " program

//Prog0: Simple yet interesting  !!  
//-------------------------------    

#include<iostream>
int main(){

std::cout<<"Hello World !"<<std::endl;
return 0;http://physicsatpu.blogspot.com/

}
This program is one of the smallest nontrivial  codes which can be written using C++ but inspite of being so it does tell a fortune's worth of language fundamentals. To gauge this, we begin with line by line dissection of the code,
  1. Code:
    //Prog0: Simple yet interesting  !!  
    //-------------------------------    

    The ('//') characters mark the beginning of a comment which extends till the end of line. Comments are ignored by the compiler but they are put in to the programs to ensure the readability and for the ease of debugging.

  2. Code:
    #include<iostream>  

    The C++ houses many of it's features in the standard library rather than making everything a part of what is called  core language. Core language features are always avaialable to the programs but one has to explicitly ask for chunks of standard library that one wants to use. The #include directive here asks for the standard library features
    from iostream. The iostream provide support for the sequential input -output and is enclosed in angular brackets since it referes to a part of standard library called standard header

  3. Code:
    int main()

    Every C++ program must contain exactly one function named main() which the implementation calls in order to run the program. A function is a piece of program that can be called from another part and  is characterised by a "name", "return type" and the "body". Name is for making a function call,
    body is the set of one or more statements enclosed in a set of curly braces ("{" and "}") containing the function implementation, and the return  type inform about the kind of value to be expected as a result of succesful call.

  4. Curly braces:
    {

    The curly braces whereever present in a C++ code tells implementation to treat the enclosed statements a a unit (compound statement). The left brace here marks the beginning of a compound statement which is the body of  main() function.

  5. Code
    std::cout<<"Hello World !"<<std::endl;

    The std::cout is the standard ouput stream used for ordinary output, and ("<<") is the output operator from standard library. The ouput operator here first writes Hello World ! and then std::endl; into the std::cout. The std::endl is another standard library object that ends the current line so that if the program sends some other output, it appears on the next line. The quotes ("") in "Hello World !" tells that this expression is a string literal (more later).

  6. Code
    return 0;
    The return statement wherever encountered, "returns" the value contained between itself and the concluding semi-colon back to the calling program and then ends the execution of the function where it( return statement ) appears. The value returned by a function must be consistent with what it says it will return. Here, int main() tells the implementation to expect a return value of type "int" (C++ keyword to flag the integer data),
    so return 0; returns a value 0, marks the succesfull running of the function, and ends the execution.

  7. Curly brace
    }
     
    Marks the end of the int main(), and thus that of the
    program execution.
Although the program we have written is very simple but already it helped us to walk a lot of the ground in the journery of becoming C++ experts. We learned about the basic program structure, core language and standard library, function definitions and ordinary input-output using string literals. Before we move further it is a good idea for the user to try wrting-compiling-running this program and also try following exercises.

    Exercise Set: 1

  • Write a program which has follwowing output:
    My name is Charlie, but I am not one of the Chaplins !!
  • Write a program to which has follwing formatted output:
             Johnny!! Johnny!!
         Yes, Papa,
         Eating Sugar ?
         No, Papa,
         Telling lie ?
         No, Papa,
         Open Mouth !!
         Ha, Ha, Haah !!!
Next we try to introduce simple calculations using C++. Just as we did in this section, we will follow an illustrated approach i.e  trying to understand the language while discussing the programs.

Two Simple Problems

An engineer or a scientist needs to program for much more than just printing outputs on the screen. So our second set of examples is more realistic. First we try hand at finding the roots of a quadratic equation, and then deal with the problem of finding the area of a circle. Begining with the quadratic equation,
ax2+bx+c=0
The solutions are well known and are given by,
x- = (-b+√(b2-4ac))/(2a) x+ = (-b+√(b2+4ac))/(2a)
Coming to the geometric problem of finding area of circle, it is given by:
Area = π(radius)2
We show the two very simple programs below to find the roots of quadratic equation and area of circle respectively.

//Prog1: A program to find roots of quadratic equation.
//-----------------------------------------------------


#include<iostream>
#include<cmath>
using namespace std;
int main(){

//Define variables to hold coefficients
  
  float a = 0;
  float b = 0;
  float c = 0;

//Ask for and then read the values of a, b and c
  std::cout<<"Enter the values of a, b and c:"<<std::endl;
  std::cin<<a<<b<<c<<std::endl;

//Calculate the discriminant
  
  float D= -1*b+std::sqrt(b*b-4*a*c);

//Calculate the solutions
  float xp = (-b+D)/2*a;
  float xm = (-b+D)/2*a;

//Spit out the solutions
  std::cout<<"x+: "<<xp<<std::endl;
  std::cout<<"x-: "<<xm<<std::endl;
}


// Prog2: A program to find the area of a circle.
// -----------------------------------------------


#include<iostream>
using namespace std;
int main(){

//define the variables.
float radius = 0;
float area = 0;

//Read the value for radius.
std::cout<<"Enter the value of radius: "<<std::endl;
std::cin>>radius;

//Calculate the area.
area = (3.14)*r*r;

//spit out the value

std::cout<<"Area of the circle is: "<<area<<std::endl;

}

Let us begin with the dissection of 'Prog1'. This program although not very robust, introduces many new things over the simple string spitters of last section.
  1. Sinppet:
    #include<iostream>

    This is so called preprocessor directive to tell the C++ compiler to include the definitions from iostream, which is a part of C++ standard library.

  2. Snippet:
    float a = 0;
    float b = 0;
    float c = 0;
    

    The lines in the snippet below define variables 'a','b' and 'c' of type 'float' which is the C++ type to store the numbers that include a decimal point, such as 0.5 (More about this in next chapter). Further these variables are then initialized to value 0 using the assignment (=).

  3. Snippet:
    std::cout<<"Enter the values of a, b and c: "<<std::endl;
    std::cin<<a<<b<<c<<std::endl;
    

    The program then uses the cout stream to send a message to output device calling for the values of the values a, b and c. Then it uses the cin stream to read the values supplied by user into the
    identifiers 'a', 'b' and 'c'. Both the cout and cin are defined inside the iostream, and the (::) is the "scope resolution" used to uniquely identify these objects.

  4. Snippet:
    float D= -1*b+std::sqrt(b*b-4*a*c);
    

    After reading the values of 'a', 'b' and 'c', we need to calculate the value of discriminant for the equation. Here the asterix ('*') is for the multiplication, ('-') for subtraction and ('+') stands for addition. The statement std::sqrt(b*b-4*a*c) is an example of 'call' for a function which is a reusable set of independent code defined outside the main(). In this case function definition resides in one of the header files and is made availalbe to our code by statement
    #include<cmath>

  5. Snippet:
    float xp = (-b+D)/2*a;
    float xm = (-b+D)/2*a;
    

    Now we use the standard formulae to calculate the values of positive and negative roots of the quadratic equation. Note the use of ('/') for division between two sets of expressions.

  6. Snippet:
    std::cout<<"x+: "<<xp<<std::endl;
    std::cout<<"x-: "<<xm<<std::endl;
    

    Finally use the cout stream to spit out the values of 'xp' and 'xm' on the screen.

Exercise Set: 2

We have made an impressive start at the basic functionality of the C++ language.Users of this tutorial should be able to write simple programs suggested in the exercises below.
  • Write a program to calculate the area, and diagonal of
    a square of side 10 cm.
  • Write a program to calculate the final position after 10 seconds of an object that starts with an inital speed 10 ms-1. (Use: Distance = Speed X Time)
  • Write a program to calculate the final position and velocity after 10 seconds of an object that starts with an inital speed 10 ms-1 and uniformly accelerate with 2 ms-1.
    (Use: s = u.t+(1/2)a.t2, v = u + a.t)

Execution Control: ifs, buts, and whiles .....

Albeit their academic significance, all the programs encountered till now are unrealistically simplified compared to most real world problems that one comes across in engineering and science. All these represent sequential (in the order of appearance), single execution of all the instructions in the code. But a real application may be require that a certain chunk of the code be executed( once , more than once or never), conditional to the satisfaction of certain logical constraints. The coding practice where we have several possible actions, one out of which is carried out depending on the outcome of some logical testing, is called branching, and when a protion of the program is executed again and again (a fixed number of times, or till some logical condition is met) it is called looping. We return to the quadratic equation problem of the last section where we calculated the discriminant D,
float D= -1*b+std::sqrt(b*b-4*a*c);
As any practitioner of science or engineering would realize that this expression becomes logicaly invalid when b2 < 4ac, since then the (b*b-4*a*c) is a negative number for which std::sqrt is not defined. Naturaly we would like to protect our program against the undefined behavior in such

  • Calculate (b*b-4*a*c)
  • If (b*b-4*a*c) < 0 : print: WARNING, EXIT
  • Else :Calculate float D= -1*b+std::sqrt(b*b-4*a*c);
  • Proceed as before
Implementation of this algorithm requires the program to make logical decisions and then execute the instruction that follow. The C++ proivde if functionality with following syntax,

if(condition)
   statement
or
if(condition)
  statement1
else
  statement2
Here the "condition" is an expression that yields a truth value which if true cause immediate next statement to be executed. In the second form if the truth value is false, the statement following else get executed. Here is the updated program,

//Prog1: A program to find roots of quadratic equation.
//Prog3: Demonstrate the use of if-else structure
//-----------------------------------------------------


#include<iostream>
#include<cmath>
using namespace std;
int main(){

//Define variables to hold coefficients
  
  float a = 0;
  float b = 0;
  float c = 0;

//Ask for and then read the values of a, b and c
  std::cout<<"Enter the values of a, b and c:"<<std::endl;
  std::cin<<a<<b<<c<<std::endl;

//Calculate (b*b-4*a*c)

  float arg = (b*b-4*a*c);

//Use if-else structure
 
  if(arg<0){
    std::cout<<"Warning: No real roots.\n Exiting"<<std::endl;
    return 1;
   }
  else{
    if(arg==0)
     std::cout<<"Both the roots are equal"<<std::endl;
    else 
     std::cout<<"Both the roots are real and distinct"<<std::endl;
  
   //Calculate the discriminant
  
    float D= -1*b+std::sqrt(b*b-4*a*c);

   //Calculate the solutions
    float xp = (-b+D)/2*a;
    float xm = (-b+D)/2*a;

   //Spit out the solutions
    std::cout<<"x+: "<<xp<<std::endl;
    std::cout<<"x-: "<<xm<<std::endl;
    return 0;
   }
}

We will now dissect this program to have a closer look at the newly introduced features.
  1. Code:
    float arg = (b*b-4*a*c);
    

    This declares a variable named 'arg' and initialize it
    to the value (b*b-4*a*c).


  2. Code:
    if(arg<0){
        std::cout<<"Warning: No real roots.\n Exiting"<<std::endl;
        return 1;
       }

    The arg<0 is a logical expression which can evaluate
    either to zero or one. If 'arg' is less than 0, this
    expression evaluates to 1, and cause the compound statement
    (chunk of code in curly brackets) following 'if' to execute.
    The code inside the brackets: the first line prints a warning
    on the screen i.e "Warning: No real roots" and second line
    cause the execution of main() function to stop and return
    a value 1.
  3. Code:
    else{
        if(arg==0)
         std::cout<<"Both the roots are equal"<<std::endl;
        else 
         std::cout<<"Both the roots are real and distinct"<<std::endl;
      
       //Calculate the discriminant
      
        float D= -1*b+std::sqrt(b*b-4*a*c);
    
        -----------------------------------
        -----------------------------------
        -----------------------------------
    
        }

    If (arg<0) described in the point 2 evaluates to false i.e arg
    IS NOT less than 0, the compound statement following 'else'
    would be executed. Once inside this block, implementation once
    again use "if(arg==0)" to check if 'arg' was equal to zero and if
    it is, the first statement is executed otherwise the second one is.
    Rest of the code has already been explained in the earlier examples.
  4. Some general observations, we have seen the use of
    "<" and "==" for comparison of the floating point
    variable to some value. They can be used to compare
    two variables as well (use: if(arg1<arg2))
    as long as both of them are of 'similar' type. Both of these
    belong to C++'s set of 'logical operators
    (<, >, ==, !, <=, >=)'
    for comparing the variables which can be used to
    implement "decision taking" while the execution.
Before we close this subsection, let us perform an elementary arithmetic drill. What shall we do if we wish to print all the natural numbers upto 200 on the screen ? Now is the time to introduce the "loop" constructs.A loop is a group of the statements that are repeated till a terminating condition is met. One of the possible looping facilities in C++ is "while", which has following syntax:

while(condition) statement

//Prog4: Program To print all natural numbers less than 200
//------------------------------------------------------------


#include<iostream>

int main(){

 //declare variable and Initialize it.
  int counter = 1;

 //Start a while statement.
  while(counter<=200){
    
   counter=counter+1;
   std::cout<<counter<<std::endl;  
  }
  return 0;  
}

//Prg5: Program To print all even numbers less than 200
//------------------------------------------------------------

#include<iostream>

int main(){

 //declare a variable and Initialize it.
  int counter = 1;

 //Start a while statement.
  while(counter<=200){
    
   counter=counter+1;
    
 //Modulo operator: gives remainder 
    //for "counter divided by two"
    double remainder =(counter%2);

 //If remainder is zero: current 
    //value of counter is even->print it.
    if(remainder == 0)
     std::cout<<counter<<std::endl;  
  }
  return 0;  
}
Keep tuned in for the next post where we introduce the notion of functions and data structures in C++ program.

DONT FORGET TO WRITE DOWN YOUR COMMENTS, IT HELPS US TO IMPROVE THE QUALITY

Monday, June 14, 2010

A Beautiful Poem

Hi All,
An extremely beautiful poem:

Umango'n ko sakhi,
pi ki nagarriya kaise le jau'n
kamar lachake mori,
ke bhaari gagariya kaise le jau'n


Dagar mein roop ke lobhi,
nagar mein man ke maile hai'n
Yaha'n paapi nazariyon ke,
hazaro'n jaal faile hai'n
Bhare'y baazar mein baa'li,
umariya kaise le le jau'n
kamar lachake mori,
ke bhaari gagariya kaise le jau'n


mohe duniya se dar la'ge
yahan lakon hai matwaa'le
njaa'ne koi albela moh'ey
kis rang mein rang daa'le
rangeelo'n mein kori
chunariyaa' kaise le jau' n
kamar lachake mori,
ke bhaari gagariya kaise le jau'n

lga'a ke haa'th mei'n menhdi
rcha ke naino'n me kajra
dulhan ban ke nikli hu'n
milege aj man basiy'a
sajan je dua'r se pya'si
gagariya le kaise jau'n

I don't know the poet, but this is a song from some very old hindi movie (may be one of those made in Lahore before independence).....the music and the rendition are even better, vist: http://www.youtube.comwatch?v=edG1l8xD1g4&feature=channel

Cheers
Sher Khan

Tuesday, March 9, 2010

Computational Physics: Future's Call ?

Using computers for the physics research has become very commonplace these days. While the software development in commercial arena often involve large teams and is well planned, it not not unusual to find physics packages developed and written by a single author. And software engineering is not a part of usual physics curriculum. So a vast body of the code done by practising physicists usually smack of inefficiency and non-reusability. Codes written without compliance to the sound principles of software engineering are usually hard to read, and debug. There usability is often restricted to the original author,
sometimes even the original context. In this backdrop it becomes imperative for the physics community to learn and start practising the disciplined way of writing the programs...and something of what is called software engineering.