I have a section of code using random.new
but the thing is that the numbers it generates, the digits in them stay the same amount of digits as the max number. Is this supposed to happen? if so, how can i get around this problem?
I have a section of code using random.new
but the thing is that the numbers it generates, the digits in them stay the same amount of digits as the max number. Is this supposed to happen? if so, how can i get around this problem?
math.random
’s seed is tick()
and it does not change. Do not specify a seed in Random.new
for the numbers to be unique.
In other words, calling math.random
several times on the same frame will result in the same number. You can fix this by moving local random
above the repeat
.
i removed the math.random inside the random variable, and moved random variable out of the function, but it still does it
You’re picking a random number between 1 and 50 billion. 40 billion of those numbers have 10 digits in them, ~10 billion of them have 9 digits or fewer.
You’re going to get a 10-digit random number literally 80% of the time.
You don’t have to create a new Random object in every repeat.
local randy = Random.new(tick()) -- Different random seed every time
repeat
local number = randy:NextInteger(1, 50000000000)
print(number)
This way, a new random number is cycled every time.
Yeah that is supposed to happen as @Offpath said.
You can visualize this as the probability of getting a 1 digit number is 9/5000000 where 9 is the total quantity of possible 1 digit values 1,2,3,4,5,6,7,8,9 and 5000000 is the upper limit.
That is a probability of 0.00018%, the probability of a 2 digit number is 99/5000000 , 3 digits is 999/5000000 and so on and you will notice these chances are really low.
So the solution should be if you are looking for even distribution of the number of digits, is to randomize the number of digits as well.
also as @DaDude_89 you should only create 1 random object to ensure the seed is the same which should ensure the outputted number is “random” quotation marks because random in computers is actually pretty complicated.
local randomGenerator1 = Random.new()
local function randomDigit(number, numberOfDigits)
local str = tostring(number)
local reducedDigit = randomGenerator1:NextInteger(1, numberOfDigits)
reducedDigit = math.min(reducedDigit, #str)
return tonumber(string.sub(str, reducedDigit, #str))
end
local randomGenerator2 = Random.new()
for i =1, 100 do
local num1 = randomGenerator2:NextInteger(1,1000000)
local numberOfDigits = math.floor(math.log10(1000000))
local num2 = randomDigit(num1, numberOfDigits)
print(num2)
end