PDA

View Full Version : Random.Range

Tim Conner
07-12-2012, 08:39 PM
I have looked over the internet and what I found never works for me I want a random range from a number to a number here is what i tried.

var value = Math.floor(Math.random() * (nb - na + 1) + na)

devnull69
07-12-2012, 10:03 PM
What is a random range?

So you want to have a range that has a random start number and a random end number and contains every number in between?

The code you showed gives you one(!) random number between (and including) na and nb

Philip M
07-12-2012, 10:37 PM
<script type = "text/javascript">
function random(lo,hi) {
return lo + Math.floor((hi-lo + 1) * Math.random() );
}

</script>

If you wish the hi and lo values to be random themselves, you must start by generating them within some desired range.

var randy1 = 0;
var randy2 = 0;
var num = 100;
while (randy1 == randy2) { // not both the same number!
var randy1 = Math.floor(Math.random() * num +1); // generates 1-100 truly randomly
var randy2 = Math.floor(Math.random() * num +1); // generates 1-100 truly randomly
}

if (randy1 > randy2) {
hi = randy1;
lo = randy2;
}
if (randy2 > randy1) {
hi = randy2;
lo = randy1;
}
alert (lo + " " + hi);

Man Pushes Melon Through ex-Partner's Catflap. - headline in Norwich Evening News

Tim Conner
07-13-2012, 04:31 PM
If its low 5 and high 6 it gives 1 though?
function roltd(low,high){

var value = Math.floor(Math.random() * (high - low + 1) + low);

document.getElementById("page").innerHTML+= value +"<br/>";
}

oneguy
07-13-2012, 08:04 PM
If its low 5 and high 6 it gives 1 though?
function roltd(low,high){

var value = Math.floor(Math.random() * (high - low + 1) + low);

document.getElementById("page").innerHTML+= value +"<br/>";
}
Do you mean that roltd(5, 6) writes 1?

Philip M
07-13-2012, 08:40 PM
If its low 5 and high 6 it gives 1 though?

Nonsense.

<script type = "text/javascript">
function roltd(low,high){
return Math.floor(Math.random() * (high - low + 1) + low);
}