EN
JavaScript - random float number in range with inclusive max value example
14 points
In JavaScript, it is possible to randomize a float number in a range with an inclusive max value in the following way.
xxxxxxxxxx
1
// Generates values from <0, 1>
2
function randomizeValue() {
3
var value = (1 + 10E-16) * Math.random();
4
5
if (value > 1.0) {
6
return 1.0;
7
}
8
9
return value;
10
}
11
12
/*
13
inclusive min (result can be equal to min value)
14
inclusive max (result will not be to max value)
15
*/
16
function randomizeFloat(min, max) {
17
if(max == null) {
18
max = (min == null ? Number.MAX_VALUE : min);
19
min = 0.0;
20
}
21
22
if(min >= max) {
23
throw new Error("Incorrect arguments.");
24
}
25
26
return min + (max - min) * randomizeValue();
27
}
28
29
// Example:
30
31
console.log(randomizeFloat()); // 1.1960373039711962e+308
32
console.log(randomizeFloat(5)); // 0.7663988388633522
33
console.log(randomizeFloat(10, 80)); // 67.81113931017913
34
console.log(randomizeFloat(-50, 50)); // -13.713816892801674