This question already has answers here:
Javascript Random Number?
(3 answers)
Closed 3 years ago.
i am using this function to generate random number between 1000 and 100.
but here according to me, in (max - min) + min, max- min =900 and min= 100, so it should not generate numbers between 900 and 100? but it is returning numbers greater than 900 also how? I am confused. and do tell how to check the range for the numbers random function is generating? any help with this?
x = Math.floor(Math.random() * (1000 - 100) + 100);
console.log(x);
The formula for random numbers Math.random() * (max - min) + min is the correct one to get a uniformly distributed number between min and max.
max - min will give you the range in which you want to generate the random numbers. So in this case 1000 - 100 results in a range of 900.
Multiplying by Math.random() will give you a random number in the range. So, with a Math.random() producing 0.5 after multiplying you get 450.
Finally, adding min back to the random pick ensures the number you get is within bounds of min and max.
For example Math.random() produces 0.01 if we substitute in the formula we get 0.01 * (1000 - 100) = 9 which is below min. Conversely, if Math.random() produces 1 then 1 * (1000 - 100) = 900 which is the highest random number possible to get from the range and yet it's still below max. In both cases adding min to the result ensures the random number you get is within max and min
The function Math.random() returns a number between 0 and 1.
When use "Math.random() * (1000 - 100)", this part of the code generates a number between 0 and 1 then multiplies it by 900, which will give you a number between 0 and 900.
Now in the last block you do add 100 to the previously generated number which results in a number between 0 and 900 + 100, which gives a result between 100 and 1000.
function random(min, max) {
console.log("Multiplying by: " + (max - min));
console.log("And adding : " + min);
return Math.floor(Math.random() * (max - min) + min);
}
console.log(random(100, 1000));
Multiply by (1000 -200) instead as you already have +100
Because in case random number generated is anything greater than 800 you end exceeding range as you're adding 100 in it everytime
x = Math.floor(Math.random() * (1000 - 200) + 100);
console.log(x);
Thumb rule :-
Math.floor(Math.random() * - ( max - ( 2 * min ) ) + min )
As Math.random() generate floats, this need to be converted to an integer.
We can use parseInt(), but there is a shorthand, the ~~ bitwise operator. Performances are known to be excellent.
console.log(
100 + ~~(Math.random() * 800)
)
One possible alternative is the web crypto api, it might be a bit slower, but with the best randomness doable. This return an integer between 0 and 256.
console.log(
100 + ~~(crypto.getRandomValues(new Uint8Array(1))[0] * 3.13)
)
Related
What JavaScript formula can I use to truncate a number to the nearest 50.
Example. I wanted 498 > 450
I have tried
Math.round (498, 50 )
And
Math.ceil(498, 50)
But am not getting. Please help
This may be a mixup of terminology, mixing terms like "nearest" and "truncate", neither of which quite describes what the example demonstrates.
The example you give always rounds down, never up, to the nearest custom value (in this case 50). To do that you can just subtract the result of % 50. For example:
const val = 498;
console.log(val - val % 50);
Even make it a re-usable function:
const Nearest = (val, num) => val - val % num;
console.log(Nearest(498, 50));
Divide by 50, do the operation, multiply by 50.
console.log(Math.floor(498 / 50) * 50);
console.log(Math.ceil(498 / 50) * 50);
console.log(Math.round(498 / 50) * 50);
console.log(Math.trunc(498 / 50) * 50);
You divide your number by 50, take the ceiling of that number and then multiply it by 50.
Math.ceil(value / 50) * 50;
A quick sidenote: truncate has a whole other meaning for numbers in Javascript: Math.trunc on MDN
Edit:
If you want other rounding semantics than ceil you can of course use floor (always goes to lowest multiple of 50):
Math.floor(451 / 50) * 50; // => 450
You divide by the multiple and round and then multiply by the multiple. If you want the lower bound, you use floor instead of round. If you want the upper bound, you use ceil instead of round. Look at these examples:
let x = 498;
let y = Math.round(498/50)*50;
console.log(y);
y = Math.floor(498/50)*50;
console.log(y);
y = Math.ceil(498/50)*50;
console.log(y);
To do what you want, the Remainder operator is your best friend. This will give you whatever is left over after dividing the number by the nearest number.
If your goal is to always round down, the following function would work. Just take your original number, find the remainder, and remove the remainder:
function roundDownToNearest(num, nearest){
return num - (num % nearest);
}
console.log(roundDownToNearest(498, 50))
If you always want to round up, you round down, then add the nearest amount:
function roundUpToNearest(num, nearest){
return num - (num % nearest) + nearest;
}
console.log(roundUpToNearest(498, 50))
If you want to get to the closest of the two, you could do the following. Find your remainder, then see if it's greater or less than half of your nearest value. If it's greater, round up. If less, round down.
function roundToNearest(num, nearest){
if(num % nearest > nearest / 2){
return roundUpToNearest(num, nearest);
} else {
return roundDownToNearest(num, nearest);
}
}
console.log(roundToNearest(498, 50))
console.log(roundToNearest(458, 50))
I have one of four possibilities for this particular variable -->
var lowVelocity = Math.random() * (45 - 30) + 30;
var medVelocity = Math.random() * (60 - 45) + 45;
var highVelocity = Math.random() * (80 - 60) + 45;
var hwyVelcoity = Math.random() * (100 - 80) +80;
In one scenario I might have either lowVelocity and medVelocity so I want to choose randomly between those two only. So I did this by:
const velocities = ["lowVelocity", "medVelocity"];
const randomUrban = Math.floor(Math.random() * velocities.length);
And this works - it now chooses one of the two velocities that I am interested in. Low velocity is between 30 and 45 and med is between 45 and 60.
In my innerHTML I want to print the number returned from that variable chosen in the array. When the user clicks this starts a function that has this in it.
document.getElementById("scenario").innerHTML = randomUrban;
But when it prints in the HTML, it doesn't print the number that is associated with the variable, it prints the array number it chose (like 0 or 1).
How do I get the variable (eg if it chose lowVelocity then the number it prints will be the random number lowVelocity found, eg 39) to print instead of the array number?
You could just use a single array to do all of this for you!
If you add the velocities to an array, then the random number can be used as an index into this array. In the code below, we use the length of this array to set the limits for the random number, then you can simply access the value from the velocities array at the position indicated by the random number:
velocities[randomUrban][1]
This gets the sub-array at the position indicated by randomUrban, and [1] gets the second element in the row, i.e. the calculated velocity.
/* Add the velocities to an array or easier management */
var velocities= [
["lowVelocity", Math.random() * (45 - 30) + 30],
["medVelocity", Math.random() * (60 - 45) + 45],
["highVelocity",Math.random() * (80 - 60) + 45],
["hwyVelcoity" ,Math.random() * (100 - 80) +80]
]
/* Pick a random position from the velocities */
const randomUrban = Math.floor(Math.random() * velocities.length);
/* Print the velocity at that position. (Also includes the velocity name for illustration) */
document.getElementById("scenario").innerHTML =
velocities[randomUrban][0] + " = " + velocities[randomUrban][1];
<div id="scenario"></div>
Note: In your example you only use 2 of the 4 velocities, so you can just add the velocities you want to choose from into the randomVelocities array.
In your case just use
document.getElementById("scenario").innerHTML = window[velocities[randomUrban]];
var lowVelocity = Math.random() * (45 - 30) + 30;
var medVelocity = Math.random() * (60 - 45) + 45;
var highVelocity = Math.random() * (80 - 60) + 45;
var hwyVelcoity = Math.random() * (100 - 80) + 80;
const velocities = ["lowVelocity", "medVelocity"];
const randomUrban = Math.floor(Math.random() * velocities.length);
console.log(randomUrban);// random from velocities
console.log(velocities[randomUrban]); //get variable name
console.log(window[velocities[randomUrban]]); // search in scope where the variables are declared in this case window
How about document.getElementById("scenario").innerHTML = velocities[randomUrban]; ?
Well, you are trying to print the wrong variable; randomUrban is the variable containing the velocities array index selected.
A quick (but pretty dirty) fix would be printing eval(velocities[randomUrban]) but eval() has been deprecated because of security issues.
A bit longer but better solution would be grouping your velocities into a single variable of type object and access its keys to retrieve the numeric value:
const velObj = {
lowVelocity: Math.random() * (45 - 30) + 30,
medVelocity: Math.random() * (60 - 45) + 45,
highVelocity: Math.random() * (80 - 60) + 45,
hwyVelocity: Math.random() * (100 - 80) + 80
};
const velocities = ["lowVelocity", "medVelocity"];
const randomUrban = Math.floor(Math.random() * velocities.length);
const velKey = velocities[randomUrban];
document.getElementById("scenario").innerHTML = velObj[velKey];
<div id="scenario"></div>
I found some code snippets and I'm not sure what it means:
var flip = Math.floor(Math.random() * (1 - 0 + 1)) + 0;
and
Math.floor(Math.random() * (max - min + 1)) + min
I'm still getting familiar with Javascript... could someone give me a reader's digest condensed version?
Math.floor() Round a number downward to its nearest integer
For example: if you have 2.7 it will round down to 2.
Math.random() Return a random number between 0 and 1
For example: .693
I know there's several questions on this, but I'm struggling to find out how to use Math.random to get random numbers between two high integers?
So, for example, between 50 and 80. I thought this would work...
'left': Math.floor((Math.random() * 80) + 50) + '%'
Any ideas?
Assuming the range is inclusive on both ends:
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
You need to know the range of the random.
Between 50 and 80, the range is 30 (80 - 50 = 30), then you add 1.
Therefor, the random would look like this :
Math.floor(Math.random() * 31) + 50
Here consider your min=50 and max = 80 refer below code:
var number = Math.floor(Math.random() * (max - min) + min);
This will solve your problem. You can try any range by changing min and max.
perc = 15/30;
//result=Math.round(perc*100)/100 //returns 28.45
$('#counter').text(perc);
$('#total').text(count);
returns back 0.5% which is suppose to be 50.00%... how do I fix this? :S
You do realize that word percent quite literally translates into "per cent" or "per 100" since cent is the latin root that's used everywhere meaning "100" or "one-hundredth".
Century (100 years)
US Cent (100th of a dollar)
Centurion (Those who commanded 100 soldiers)
Centipede (creature with 100 legs)
So 50% becomes 50 per cent becomes 50 per 100
And, since in mathematical terms, the word per means divide (miles per hour == mph == m/h) then we can distill 50% down to:
50/100
Which, surprisingly enough, is represented as the decimal number .5
15/30 = 0.5
if you want to have percent number you have to multiply it by 100.
I am a low rep user so here goes. http://en.wikipedia.org/wiki/Percentage
Treat the % sign as a constant equal to 0.01. Thus, when working with a number like 50%, treat it as 50 * 0.01 or 0.5.
0.5 = n % // I want to know what 0.5 is as a percent
0.5 / % = n * % / % // Divide both sides by the constant
0.5 / % = n // Remove the excess
0.5 / 0.01 = n // Replace the constant
50 = n // You have your answer
Just multiply by 100.