Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random numbers in a range

This is in Delphi (7 to be exact). How can I generate random numbers within a specific range? Similar to random.randint(1,6) in Python. I'm trying to simulate rolling dice. The other option is to somehow exclude 0.

Currently I have:

Randomize;
Roll := Random(7);
Label3.Caption := IntToStr(Roll);
like image 720
Aaron Avatar asked Oct 27 '11 16:10

Aaron


People also ask

How do I randomize numbers in a range in Excel?

Select the cells in which you want to get the random numbers. In the active cell, enter =RAND() Hold the Control key and Press Enter. Select all the cell (where you have the result of the RAND function) and convert it to values.


2 Answers

You can use

RandomRange(1, 7)

which will return a random integer from the set {1, 2, 3, 4, 5, 6}.

(uses Math)

[By the way, it is trivial to 'somehow' exclude zero. Just do Random(6) + 1.]

like image 113
Andreas Rejbrand Avatar answered Nov 14 '22 02:11

Andreas Rejbrand


Also, it is possible to generate a value from a float range [a, b), exluding b:

r := random;
x := (b-a)*r + a;

The first line generates a value from [0; 1) interval; the second one gives a value from [a, b).

If you want to get N random values within interval [a; b] (for example, 5 random values from interval [1; 2]: {1, 1.25, 1.5, 1.75, 2}) use the following:

r := RandomRange(0, N-1);
x := a + r*(b-a)/(N-1);
like image 42
Ivan Z Avatar answered Nov 14 '22 04:11

Ivan Z