How can I get a random integer using the random()
function in p5.js?
For example this code:
var num = random(0, 1);
console.log(num);
outputs decimal numbers to the console.
How can I get a random integer?
How can I get a random integer using the random()
function in p5.js?
For example this code:
var num = random(0, 1);
console.log(num);
outputs decimal numbers to the console.
How can I get a random integer?
Share Improve this question edited Apr 3, 2019 at 22:00 Charlie Wallace 1,8301 gold badge15 silver badges17 bronze badges asked Dec 30, 2017 at 22:43 Nil folquer covarrubiasNil folquer covarrubias 1391 gold badge2 silver badges7 bronze badges4 Answers
Reset to default 10If you want integer numbers from 0 to 10, both inclusive:
function setup() {
var num = int(random(0, 11));
print(num);
}
<script src="https://cdnjs.cloudflare./ajax/libs/p5.js/1.6.0/p5.js"></script>
Explanation:
random(0, 11)
returns numbers from 0 to 10.999999999..., but never 11.
int()
converts those decimal numbers to integer
int(random(0, 11))
returns numbers between 0 and 10, both inclusives.
Why not use simple JavaScript as demonstrated here?
Excluding max value:
function getRndInteger(min, max) {
return Math.floor(random(min, max)) + min;
}
Including limits:
function getRndInteger(min, max) {
return Math.floor(random(min + 1, max)) + min;
}
The p5.js random()
function will always return a floating-point number (aka. decimal number). If you want an integer you can use JavaScript Math.round()
to round the number to the nearest whole number.
To get a zero or one. The best method is:
Math.round(random());
You can also use int() to have JavaScript convert the number to an integer but it has a major problem where it simply ignores the decimals, in effect rounding the number down.
This is a problem with p5.js random()
because random()
will return a random number from the minimum up to but not including the maximum. The maximum of random(0, 1)
is 0.99999... which int()
always converts to 0;
This means for example:
random()
will never return 1. Meadingint(random())
always returns 0random(0, 15)
will never return 15. Meaningint(random(15))
would never return 15
So, how I would do this, is assign a floored random number to a variable.
E.G.
var r = Math.floor(random(0,11));
console.log(r);
-Valkyrie