0

I'm working on After Effetcs expressions. I'm trying to use random function to return 1 or -1 but never 0.

I need to return integers range between 10 to 20 or between -20 to -10.

It seems to be simple, but I dont find how to do that. Any idea ?

Thanks for your help !

Maynemiz
  • 1
  • 2
  • 2
    Possible duplicate of [Generate random number between two numbers in JavaScript](https://stackoverflow.com/questions/4959975/generate-random-number-between-two-numbers-in-javascript) – Patrick Hund Sep 26 '18 at 12:45
  • 2
    You want to return ONLY `1` or `-1` or you want to return any real number between them (e.g. `0.123`) as long as it's not zero? If it's the former, what's wrong with `Math.random() < 0.5 ? 1 : -1`? – VLAZ Sep 26 '18 at 12:47
  • 4
    `console.log(Math.random() < 0.5 ? 1 : -1)` – Adam Sep 26 '18 at 12:47
  • Check this url https://stackoverflow.com/questions/1527803/generating-random-whole-numbers-in-javascript-in-a-specific-range – Akip Sep 26 '18 at 12:49

4 Answers4

4

You could take a factor of two and replace zero with -1.

function random() {
   return Math.floor(Math.random() * 2) || -1;
}

var i = 10;

while (i--) console.log(random());
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • It's not worth another answer, but as an aside for the case being mentioned you could also use bitwise OR 0 instead of `Math.floor` - a.e. : `return Math.random()*2|0||-1;` – zfrisch Sep 26 '18 at 15:36
2

I stole some inspiration from Getting a random value from a JavaScript array

var myArray = [1, -1]
var rand = myArray[Math.floor(Math.random() * myArray.length)];
console.log(rand);

Put whatever number you want into that array.

Elias
  • 3,592
  • 2
  • 19
  • 42
Joey Gough
  • 2,753
  • 2
  • 21
  • 42
0

All answers to this point are good but I thought I might still add this :)

console.log("1 or -1: ", (()=>{if(Math.random() > 0.5) return 1; else return -1})())
console.log("Between 10 and 20: ", Math.floor(Math.random()*11+10));
console.log("Between -10 and -20: ", Math.floor(Math.random()*11+10) * -1);
Elias
  • 3,592
  • 2
  • 19
  • 42
0

Thanks a lot for those answers. I used something like this and it's working, but maybe it's not perfect :

random(10,20)*(Math.round(random())-0.5)*2

I'm not sure that the probability of getting 1 or -1 is exactly 1 in 2.

Maynemiz
  • 1
  • 2