Saturday 2 March 2013

Random Number Generation


The elements of change can be introduced through the random method.
Consider the following statement
            double value = Math.random( );
The random( ) method generates a double value from 0.0 to 1.0(not included).  The range of values produced directly by random is often different than what is needed in a specific application.

Example: A program that stimulates rolling six-sided die would required random integers in the range (1,6)
            The general formula for this type of problems using random method is a+(int)(Math.random( )*b).  Where ‘a’ is a shifting value that is equal to the fist number in the range of integers and ‘b’ is the scaling factor that is equal to the width of range of the integer.

class random
{
            public static void main(String[] args)
            {
                        for(int i=1;i<=20;i++)
                        {
                        int s=1+(int)(Math.random()*6);
                        System.out.print(s);
                        if(i%5==0)
                        System.out.print("\n");
                        }
            }
}

No comments:

Post a Comment