Tuesday, May 24, 2011

Add 2 Numbers without using operator

Addition of 2 numbers without using '+' operator:

Algorithm :
(1) Given two numbers X and Y
(2) Check if addend (i.e. X) is 0 or not.
(3) If Addend is 0 (i.e X == 0) then return Y
     Else do the following :
    (3.1) Repeat this algorithm from step (1) by replacing X and Y as follows:
             X = ( X & Y ) << 1 [ Left Shift the result of ( Bitwise and X , Y) by 1]
             Y = ( X ^ Y ) [ Bitwise XOR of X, Y]
       
 Note: If X is a number equal to 2 power 'n', then X & Y will be always 0

C Program:

#include <stdio.h>

int add(int x, int y)
{
        if(!x) return y;
        else
         {
                //printf("\nIn Add N1: %d, N2: %d", x, y);
                return add((x & y) << 1,x ^ y);
         }
}

int main()
{
        int x, y;
        printf("\nEnter X and Y values: ");
        scanf("%d %d",&x,&y);
        printf("\nEntered values are X = %d, Y = %d \n",x,y);
        int z = 0;
        //z = ~x;
        //printf("z is %d", z<<1);
        printf("\nSum is %d\n\n",add(x,y));
        return 0;
}

 

Sub 2 Numbers without using operator

Subtract 2 Numbers without using '-' operator.

The algorithm for Subtract is same as Algorithm for Addition except we need to pass the values as follows:
Algorithm:
(1) Given two number X and Y
(2) Call Add algorithm by passing arguments as X and 2's complement of Y


C Program:
#include <stdio.h>

int add(int x, int y)
{
        if(!x) return y;
        else
         {
                printf("\nIn Add N1: %d, N2: %d", x, y);
                return add((x & y) << 1,x ^ y);
         }
}

int sub(int x, int y)
{
        //We need to pass 2nd argument as 2's complement of Y
        // i.e. add(~y,1) == 2's complement of Y
        return add(x, add(~y,1));
}

int main()
{
        int x, y;
        printf("\nEnter X and Y values: ");
        scanf("%d %d",&x,&y);
        printf("\nEntered values are X = %d, Y = %d \n",x,y);
        printf("\nSub : X - Y:  %d - %d = %d\n\n",x, y, sub(x,y));
        return 0;
}


Thursday, May 19, 2011

Code Coverage

What is Code Coverage
Code coverage is a measure used in software testing. It describes the degree to which the source code of a program has been tested. It is a form of testing that looks at the code directly and as such comes under the heading of white box testing.Currently, the use of code coverage is extended to the field of digital hardware, the contemporary design methododology of which relies on Hardware description languages (HDL’s). Code coverage techniques were amongst the first techniques invented for systematic software testing. The first published reference was by Miller and Maloney in Communications of the ACM in 1963.
In simple words “A code coverage tool simply keeps track of which parts of your code get executed and which parts do not“. Usually, the results are granular down to the level of each line of code.  So in a typical situation, you launch your application with a code coverage tool configured to monitor it.  When you exit the application, the tool will produce a code coverage report which shows which lines of code were executed and which ones were not.  If you count the total number of lines which were executed and divide by the total number of lines which could have been executed, you get a percentage.  If you believe in code coverage, the higher the percentage, the better.  In practice, reaching 100% is extremely rare.
The person who is very new to code coverage may came across with so many doubts like
“Why should we have to use code coverage”
“What are the benefits we are getting out of it”
So in the following sections, these questions will be answered.


Value of Code Coverage
provides a quantitative measurement of testing efforts.
Can assist in directing the tester’s future efforts.
Can demonstrate redundancy in test cases.
Can be used as entry/exit criteria between test phases.

Code coverage in practice
Usually the source code is instrumented and run through a series of tests. The resulting output is then analysed to see what areas of code have not been exercised, and the tests are updated to include these areas as necessary. Combined with other code coverage methods the aim is to develop a rigorous yet manageable set of regression tests. Code coverage is ultimately expressed as a percentage, as in “We have tested 63% of the code.” The meaning of this depends on what form(s) of code coverage have been used, as 63% path coverage is more comprehensive than 63% statement coverage. The value of code coverage as a measure of test quality is debated.
 

What is  meant by instrumenting the code
Instrumentation means inserting some type of code in the source code or in the byte code, so that it can ensure that all lines of code in the design have been executed
There are many approaches to code coverage measurement. Broadly there are three approaches, which may be used in combination:
Source Code Instrumentation This approach adds instrumentation statements to the source code and compiles the code with the normal compile tool chain to produce an instrumented assembly.
Intermediate code Instrumentation Here the compiled class files are instrumented by adding new bytecodes and a new instrumented class generated.
Runtime Information collection This approach collects information from the runtime environment as the code executes to determine coverage information
To know further information about how instrumentation works in Visual Studio, you can refer to this link
http://blogs.msdn.com/phuene/archive/2007/05/03/code-coverage-instrumentation.aspx


Coverage criteria
To measure how well the program is exercised by a test suite, one or more coverage criteria are used. There are a number of coverage criteria, the main ones being:
* Function coverage – Has each function in the program been executed?
* Statement coverage – Has each line of the source code been executed?
* Condition coverage – Has each evaluation point (such as a true/false decision) been executed?
* Path coverage – Has every possible route through a given part of the code been executed?
* Entry/exit coverage – Has every possible call and return of the function been executed?
For more information regarding coverage criteria refer to the following links:
http://www.bullseye.com/coverage.html
http://www.javaranch.com/journal/2004/01/IntroToCodeCoverage.html


Fooling yourself
Every now and then, I meet somebody who thinks that a body of code is perfect if its unit tests all pass with 100% code coverage.  This obviously isn’t true.  Code coverage can only tell you how much of your code is being tested.  It cannot tell you how much code you still need to write.
And in turn, some folks think that because 100% code coverage cannot be understood to mean 100% correctness, then code coverage isn’t worth anything at all.  To me, that’s like saying we should never talk about the temperature outside because by itself it is not a reliable way of determining how nice the weather is.
Unit testing and code coverage are tools.  They provide us a way of increasing the quality of our code, but 100% code coverage certainly does not mean 100% code quality.  If you want a complete QA effort, one which offers you high confidence that your code is reliably doing whatever you want it to do, then unit testing and code coverage are just a small part of the story.  There are many other tools and techniques you should consider.

External links


TOOLS
IBM Rational Application Developer can profile Java application for Code Coverage analysis
IBM Rational Test RealTime can profile embedded software for Code Coverage analysis and more
LDRA Testbed measures statement coverage, branch/decision coverage, LCSAJ Coverage, procedure/function call coverage, branch condition coverage, branch condition combination coverage and modified condition decision coverage (MC/DC) for D0-178B Level A.
Netbeans Code Coverage Plugin: emma-based coverage plugin for Netbeans the visualizes unit tests coverage by coloring sources
CodeCover: Extensible code coverage tool supporting Java and COBOL Supports statement coverage, branch coverage, loop coverage and strict condition coverage, fully integrated into Eclipse and licensed under the EPL.
Dynamic Code Coverage: Code coverage tool for Unix C/C++


Quotes


Some Inspirational Quote's
 
Every flower must grow through dirt.
– Anonymous
Worrying is like a rocking chair, it gives you something to do, but it doesn’t get you anywhere.
– Anonymous
 
Pleasure in the job puts perfection in the work.
– Aristotle
We are what we repeatedly do. Excellence, then, is not an act, but a habit.
– Aristotle
Motivation will almost always beat mere talent.
– Norman R. Augustine
Imagination is the highest kite one can fly.
– Lauren Bacall
Not everything that is faced can be changed, but nothing can be changed until it is faced.
– James Baldwin
I don’t know anything about luck. I’ve never banked on it, and I’m afraid of people who do. Luck to me is something else; hard work and realizing what is opportunity and what isn’t.
– Lucille Ball
The great advantage of being in a rut is that when one is in a rut, one knows exactly where one is.
– Arnold Bennett
Having once decided to achieve a certain task, achieve it at all costs of tedium and distaste. The gain in self-confidence of having accomplished a tiresome labor is immense.
– Thomas Arnold Bennett
Be like a postage stamp. Stick to one thing until you get there.
– Josh Billings
He who kisses the joy is it flies lives in eternity’s sunrise
– William Blake
Action springs not from thought, but from a readiness for responsibility.
– Dietrich Bonhoeffer
Character may be manifested in the great moments, but it is made in the small ones.
– Phillip Brooks
Shoot for the moon. Even if you miss, you’ll land among the stars
– Les Brown
We got to roll with the punches, play all of our hunches, make the best of whatever comes your way. Forget that blind ambition, learn to trust your intuition — plowing straight ahead, come what may.
– Jimmy Buffett, Cowboy in the Jungle (song)
Not knowing when the dawn will come, I open every door.
– Emily Dickinson
Genius is 99 percent perspiration and 1 percent inspiration.
– Thomas Edison
Everything that is really great and inspiring is created by the individual who can labour in freedom.
– Albert Einstein
In the middle of difficulty lies opportunity.
– Albert Einstein
It is never too late to be what you might have been.
– George Eliot
A problem is a chance for you to do your best.
– Buke Ellington
Do not go where the path may lead, go instead where there is no path and leave a trail.
– Ralph Waldo Emerson
Nothing great was ever achieved without enthusiasm.
– Ralph Waldo Emerson
Nothing is beneath you if it is in the direction of your life.
– Ralph Waldo Emerson
Vitality shows in not only the ability to persist but the ability to start over.
– F. Scott Fitzgerald
Life is a series of experiences, each one of which makes us bigger, even though it is hard to realize this. For the world was built to develop character, and we must learn that the setbacks and griefs which we endure help us in our marching onward.
– Henry Ford
Obstacles are those frightful things you see when you take your eyes off your goal.
– Henry Ford
One of the greatest discoveries a man makes, one of his great surprises, is to find he can do what he was afraid he couldn’t do.
– Henry Ford
You can’t build a reputation on what you are going to do.
– Henry Ford
He that would have the fruit must climb the tree.
– Thomas Fuller, M.D.
We must become the change we want to see.
– Gandhi
Whatever you do will be insignificant, but it is most important that you do it.
– Gandhi
Treat people as if they were what they ought to be, and you help them to become what they are capable of being.
– Johann Wolfgang von Goethe
What does not kill me makes me stronger.
– Johann Wolfgang von Goethe
Whatever you can do or dream you can, begin it. Boldness has genius, power, and magic in it.
– Johann Wolfgang von Goethe
When we treat man as he is, we make him worse than he is; when we treat him as if he already were what he potentially could be, we make him what he should be.
– Johann Wolfgang von Goethe
Every calling is great when greatly pursued.
– Oliver Wendell Holmes
The greatest mistake you can make in life is to be continually fearing that you will make one.
– Ellen Hubbard
May the road rise to meet you. May the wind always be at your back. May the sun shine warm upon your face, the rains fall soft upon your fields and, until we meet again, may God hold you in the palm of his hand.
– Irish Blessing
Keep your face to the sunshine and you cannot see the shadow.
– Helen Keller
When we do the best that we can, we never know what miracle is wrought in our life, or in the life of another.
– Helen Keller
There are those who look at things the way they are, and ask why… I dream of things that never were, and ask why not?
– Robert Francis Kennedy
He who limps is still walking.
– Stanislaw J. Lec
Whatever you are, be a good one.
– Abraham Lincoln
It’s not whether you get knocked down, it’s whether you get back up.
– Vince Lombardi
Most of our obstacles would melt away if, instead of cowering before them, we should make up our minds to walk boldly through them.
– Orison Swett Marden
We are not in a position in which we have nothing to work with. We already have capacities, talents, direction, missions, callings.
– Abraham Maslow
Victory belongs to the most persevering.
– Napoleon Bonaparte
As for courage and will – we cannot measure how much of each lies within us, we can only trust there will be sufficient to carry through trials which may lie ahead.
– Andre Norton
Chance is always powerful. – Let your hook be always cast; in the pool where you least expect it, there will be a fish.
– Ovid
Remember your dreams.
– Maryanne Radmacher-Herhey
To achieve the impossible, it is precisely the unthinkable that must be thought.
– Tom Robbins, Jitterbug Perfume
Fanaticism consists of redoubling your efforts when you have forgotten your aim.
– George Santayana
Every new beginning comes from some other beginning’s end.
– Semisonic, Closing Time
It is not because things are difficult that we do not dare; it is because we do not dare that they are difficult.
– Seneca
Curiosity will conquer fear even more than bravery will.
– James Stephens
If you want to sing out, sing out, and if you want to be free, be free, ’cause there’s a million ways to be, you know that there are…
– Cat Stevens, from a song lyric
Never give up, for that is just the place and time that the tide will turn.
– Harriet Beecher Stowe
Can you imagine what I would do if I could do all I can?
– The Artist Formerly Known As Prince
Once all struggle is grasped, miracles are possible.
– Mao Tse-tung
Opportunities multiply as they are seized.
– Sun Tzu
The mind has exactly the same power as the hands: not merely to grasp the world, but to change it.
– Colin Wilson
Success is peace of mind which is a direct result of self-satisfaction in knowing you did your best to become the best you are capable of becoming.
– John R. Wooden, Practical Modern Basketball
Do or do not. There is no try.
– Yoda, character in the movie The Empire Strikes Back
Obstacles cannot crush me. Every obstacle yields to stern resolve. He who is fixed to a star does not change his mind.
– Leonardo da Vinci, Notebooks

Wednesday, May 18, 2011

Random Number Generator Algorithm


Random Number Generator: 

Hello Friends,


So what are random numbers ?
Anyone will answer this question as "Random numbers are numbers which are generated randomly".
My way of answering this Q is "Numbers which are generated in such a way that does not have any pattern are called Random numbers"

We have seen in many applications where random number generator algorithm is used such as in gaming application, cryptography, etc. For example, shuffling of playing cards, dice, etc. There are built-in functions in any language to generate random numbers, but do we really know how does random function works?

Whatever values we generate in computational science are mostly Pseudo Random Numbers, which are generated by deterministic procedure. To generate True Random Number we need to use some kind of physical phenomenon like radioactive decay, thermal noise, etc.

Some of the Pseudo Random Number Generators are :
  • Linear Congruential Generator
  • Blum Blum Shub
  • Multiple With Carry
  • Inverse Congruential Generator
  • Lagged Fibonacci Generator

As we generate Pseudo Random Numbers using some deterministic procedure which in turn depends on fixed number called seed (Random Seed) which is used to initialize the Pseudo Random Number Generator. The most common type of Pseudo Random Number Generator is Linear Congruential Generator whose recurrence relation is:


where Xn is the sequence of pseudo random values, and

           m, 0 <    m        — the "modulus"
           a,  0 <    a < m  — the "multiplier"
           b,  0 <=  b < m — the "incrementer"
 X_0,\,0 \le X_0 < m — the "seed" or "start value"
are integer constants that specify the generator.
The pattern (period) at which same numbers can be repeatable is at most "m". Linear Congruential Generator have full period for all seed values iff (where c is non zero) :
  1. b and m are relatively prime,
  2. a - 1 is divisible by all prime factors of m,
  3. a - 1 is a multiple of 4 if m is a multiple of 4

One of the simple way to understand what Pseudo Random Generator's are by using example described by John Von Neumann is middle-square method. This method describes as if we want to generate 6-digit random number, let it be 675248 (which is seed) and take square of that number which will be 12-digit number (if square of the number is less than double the digits of original number then leading digits are added to compensate ). Then random number for the given seed will be middle 6-digit number (which will also acts as the seed value for the next random number)


http://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Middle-square_method.svg/250px-Middle-square_method.svg.png

 The drawback with the above approach is that if we got the random number as all zero's , then next all generated random numbers are going to be always zero. For example, if we got the current random number as 0000, then the next random numbers are always 0000 only. For a generator of n-digit numbers, the period can be no longer than 8n


Hope you have understood the concept of random number generator. Comments are appreciated on this topic