Math.random() exclude 0

I use math.random(-1,1) so that I can randomize if my original number is positive or negative. Is it possible to exclude 0? Thanks!

You could just do something like

math.random(0,1)*2 - 1
5 Likes

Another solution is that you can use you can add the positive and negative integers in a table and get a random index in the table. Here is a basic example:

local numbers = {-1, 1}
print(numbers[math.random(#numbers)])
3 Likes

math.random when specified with two values returns a number in the range [m, n]. -1 < 0 < 1 therefore 0 is a valid number in this range. You can’t exclude a number, so your best bet would be to do randomise again until the result is not 0.

If you’re working with small numbers then I guess something like the above would work but that wouldn’t be as applicable or efficient if you’re expecting decimal numbers or larger min-max sets, which then again you could just randomise until the number isn’t 0.

3 Likes

I am indeed working with small numbers, so there solutions should work fine. Thank you for the advice though, I’ll make sure to remember this for the future.

Thanks everyone for the contribution. I didn’t know it was so simple!