comp102 lec 5.0

12
Random Numbers http://www.cs.geneseo.edu/~baldwin/reference/random.html

Upload: fraz-bakhsh

Post on 25-May-2015

136 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Comp102   lec 5.0

Random Numbers

•http://www.cs.geneseo.edu/~baldwin/reference/random.html

Page 2: Comp102   lec 5.0

Two Methods

By using Random Library ClassBy using Math Library Class

Page 3: Comp102   lec 5.0

RANDOM CLASS

Page 4: Comp102   lec 5.0

Random Class

To use a classImport the class library

import java.util.Random;OR

import java.util.*;

Create an object of classRandom “name of object” = new Random()E.g

•Random rand = new Random();

Page 5: Comp102   lec 5.0

Generate a Random Number Integer

Have/Declare an integer variableint a;

Assign it a random valuea=“object”.nextInt(“Value to define Range”);E.g

a = rand.nextInt(100);If value is 100, range is 0 – 99Value will define the range as starting from 0 to one less than the value

Page 6: Comp102   lec 5.0

Define Ranges, where A is an Integer and rand is Random Object

A = rand.nextInt(100)A = rand.nextInt(10)A = rand.nextInt(101)A = rand.nextInt(99)A = rand.nextInt(100) + 5A = rand.nextInt(100) – 10A = rand.nextInt(10) + 1A = rand.nextInt(101)+5A = rand.nextInt(10) -10

0 - 990 - 90 - 1000 - 980 – 99 and then add 5 to it => 5-1040 -99 and then subtract 10 => -10 – 890 – 9 and then add 1 => 1 - 100-100 and then add 5 => 5 - 1050-9 and then subtract 10 => -10 – (-1)

Page 7: Comp102   lec 5.0

What if I have to generate a Random Number from 0 – 50,

both inclusiveA = rand.nextInt(50);A = rand.nextInt(51);A = rand.nextInt(100)-50;A = rand.nextInt(50)+1;

Will generate a random number

from 0 -49Will generate a random

number from 0 - 50

Will generate a Random Number from 0 – 99 first

and then subtract 50 from generated number

thus defines the range as[0 – 50] – [99 – 50] =

-50 - 49

Will generate a random number from 0 – 49 and then will add 1 to it, makes

range as 1 – 50

Page 8: Comp102   lec 5.0

What if I have to generate a Random Number from 5 – 15

both inclusive?a = rand.nextInt(15);a = rand.nextInt(16);a = rand.nextInt(10)+5;a = rand.nextInt(11)+5;

Page 9: Comp102   lec 5.0

Random Real Numbers

To generate a random real number uniformly distributed between 0 and 1, use the "nextDouble" message. This message takes no parameters. For example...double r = rand.nextDouble();

Page 10: Comp102   lec 5.0

CLASS MATH

Page 11: Comp102   lec 5.0

Math.random() call

double x = Math.random();Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.Will assign a value to x from [0.0 – 0.999]

Page 12: Comp102   lec 5.0

Generate Integer Random Number

Math.random()*10[0.0 – 9.99]Convert it into Integer by type casting

(int)(Math.random()*10)[0 – 9]

Math.random()*100[0.0 – 99.99]Convert it into Integer by type casting

(int)(Math.random()*100[0 – 99]