|
|
|
|
Reply From: |
batmanasb |
randi()%10+1
returns an int
from 1 to 10
randf()*10.0+1.0
returns a float
from 1.0 to 10.999999~
rand_range(1,11)
returns a float
from 1.0 to 10.999999~
range(1,11)[randi()%range(1,11).size()]
is a little ugly and less efficient but returns an int
from 1 to 10 without you having to do the math yourself (aka the 11+1 part) because all you need to do is set the range()
Answer changed due to more info
The_Duskitty | 2016-04-02 23:44
Yay I won! Take that tiernich!
batmanasb | 2016-04-03 01:23
lol - defeat accepted
tiernich | 2016-04-03 03:13
To get a random integer between 1 and 10, I find it more intuitive to floor the random float in range. More specifically:
floor(rand_range(1, 11))
Oranjoose | 2016-04-16 20:32
randi()%11+1 is probably biased towards lowest values of 1…10
Omicron | 2017-03-08 09:35
I’m trying to generate a random between 10-30 (randi()%30+10) but it’s giving me a 35. Probably doing it wrong, but can’t figure out how to make it right.
Rodrigo Maller Marti | 2017-05-24 00:11
try (randi()%30)+10
Omicron | 2017-05-24 05:48
Don’t forget to call randomize
jarlowrey | 2017-06-01 15:39
This answer has an important error. If you want to produce a real number in the interval [x,y[, in general you use:
(randf() * (y-x)) + x.
From 1 to 10, you have randf() * 9 + 1
. This is because randf()
can be 1 as maximum. In this case, you would obtain 9 + 1 = 10. In the case proposed by this answer, randf() * 11 + 1
, if by chance randf()
turns out to be greater than 0.8 you get something greater than 10. So, there is a 20% chance of having a wrong answer.
VictorSeven | 2017-09-05 18:00
randi()%11+1 returns an int from 1 to 11
If you someone needs a random int between 1 and 10, use:
randi()%10+1
leo_frozen | 2018-11-09 02:20
Please note that randi()%11+1 return a number between 1 and 11 not 10
because randi()%11 can be 10 and adding 1 to it will make it 11. the same thing for randf()
yes indeed, obviously and i don’t know how we could go so wrong
Omicron | 2020-05-03 09:07
Corrected the inaccuracies. The random floats won’t return a 1.0, but at most .999999~.
The last method using arrays I left, but would recommend int(rand_range(1,11))
as an alternative.
avencherus | 2020-05-05 13:47