Home > OS >  Lua: How do I calculate a random number between 50 and 500, with an average result of 100?
Lua: How do I calculate a random number between 50 and 500, with an average result of 100?

Time:10-28

I think this is a log-normal distribution? I'm not sure. The lua I have is here:

local min = 50
local max = 500
local avg = 100
local fFloat = ( RandomInt( 0, avg ) / 100 ) ^ 2 -- float between 0 and 1, squared
local iRange = max - min -- range of min-max
local fDistribution = ( ( fFloat * iRange )   min ) / 100
finalRandPerc = fDistribution * RandomInt( min, max ) / 100

It is close to working, but sometimes generates numbers that are slightly too large.

CodePudding user response:

This can be done in literally infinite number of ways. One other approach is to generate a number from binomial distribution, multiply with 450 and add 50. I will leave the task of finding the right parameters for the binomial distribution to you.

CodePudding user response:

How do I calculate a random number between 50 and 500, with an average result of 100?

You can use Chi-squared of degree 4 with its tail removed.
It is very easy to calculate.

local function random_50_500()
   -- result is from 50 to 500
   -- mean is very near to 100
   local x
   repeat
      x = math.log(math.random())   math.log(math.random())
   until x > -18
   return x * -25   50
end
  • Related