This is a pretty simple Java (though probably applicable to all programming) question:
Math.random()
returns a number between zero and one.
If I want to return an integer between zero and hundred, I would do:
(int) Math.floor(Math.random() * 101)
Between one and hundred, I would do:
(int) Math.ceil(Math.random() * 100)
But what if I wanted to get a number between three and five? Will it be like following statement:
(int) Math.random() * 5 + 3
I know about nextInt()
in java.lang.util.Random
. But I want to learn how to do this with Math.random()
.
Output of
randomWithRange(2, 5)
10 times:The bounds are inclusive, ie [2,5], and
min
must be less thanmax
in the above example.EDIT: If someone was going to try and be stupid and reverse
min
andmax
, you could change the code to:EDIT2: For your question about
double
s, it's just:And again if you want to idiot-proof it it's just:
If you want to generate a number from 0 to 100, then your code would look like this:
To generate a number from 10 to 20 :
In the general case:
(where
lowerbound
is inclusive andupperbound
exclusive).The inclusion or exclusion of
upperbound
depends on your choice. Let's sayrange = (upperbound - lowerbound) + 1
thenupperbound
is inclusive, but ifrange = (upperbound - lowerbound)
thenupperbound
is exclusive.Example: If I want an integer between 3-5, then if range is (5-3)+1 then 5 is inclusive, but if range is just (5-3) then 5 is exclusive.
The
Random
class of Java located in thejava.util
package will serve your purpose better. It has somenextInt()
methods that return an integer. The one taking an int argument will generate a number between 0 and that int, the latter not inclusive.Here's a method which receives boundaries and returns a random integer. It is slightly more advanced (completely universal): boundaries can be both positive and negative, and minimum/maximum boundaries can come in any order.
In general, it finds the absolute distance between the borders, gets relevant random value, and then shifts the answer based on the bottom border.
To generate a number between 10 to 20 inclusive, you can use
java.util.Random