I need to generate a random number that's between -40 and -10 and 10 and 40. So the results could be 25, but never -5 or 5.
I've looked online, but the solutions seem overly complex. Is there any way to do it in just one or two lines?
I need to generate a random number that's between -40 and -10 and 10 and 40. So the results could be 25, but never -5 or 5.
I've looked online, but the solutions seem overly complex. Is there any way to do it in just one or two lines?
Math.random() will return a random number between 0 and 1.
Create your own function to create a random number between your min and max numbers. Scale a random number between your min and max, then offset by you min value.
function randomBetween(min, max) {
return Math.random() * (max - min) + min;
}
Generate a number between 10 and 40 and then generate a 1 or 0, if 0 convert it to negative 1 and multiply by either result
Math.random() * 30 + (Math.random() < 0.5 ? -40 : 10);
var n = Math.random()*62;
return n - (n < 31 ? 40 : 21);
for(int i=15;i<=46;i++)
{
double random=Math.rand()*5+i;
int rand=(int)random;
System.out.println(rand);
}
The above code generates the random number between 15-50
Math.random()*5=i
This gives the lower value i.e 15 here in this case
Note: you need to subtract 4 from the upper bond of the value i.e here if u use i<=50 this will be printing no up to 54 , similarly if you want to generate no. b/w 50-80 use (int i=50;i<=76;i++)
hope this helped :)
Short Answer:
It could be tricky but definitely the best way is to write your own function.
var random = (Math.random() - 0.5) * 2;
if (random >= 0){
random = lerp(10, 40, random);
} else {
random = lerp(-40, -10, Math.abs(random));
}
function lerp (min, max, value){
return (1 - value) * min + value * max;
}
Explanation:
There are (3) three steps you need to follow in order to achieve what you need.
A random number (between -1 and 1).
let random = (Math.random() - 0.5) * 2
An if condition to know if the value is negative or positive.
if (random >= 0){ /* Is Positive */ }
else { /* Is Negative */ }
Lerp between the values you need (-40 to-10 if negative or 10 to 40 if positive).
// This function interpolates between two numbers based on a normalized value (between 0 and 1)
function lerp (min, max, value){
return (1 - value) * min + value * max;
}
The algorithm is (rand*(max-min))+min
Math.floor(Math.random()*30)+10
and
Math.floor(Math.random()*-30)-10