Home > Software design >  I made a random number generator, is it good enough or can I make it more randomized?
I made a random number generator, is it good enough or can I make it more randomized?

Time:03-18

local z = 50 -- you can change this to the maximum value

local function ARN() -- function starts
local x = math.random(0,z) -- main number
local y = math.random() -- decimal number
local v = (x-(y)) -- I remove y's value from x
print(v) -- I then print it
return v, x, y -- return the values
end

ARN() -- calling the function

I basically made it random with decimal numbers too. I don't know if there is anything to make it more randomized. Also, I'm new to programming, so maybe some tips could be helpful too!

CodePudding user response:

math.random() already returns a floating-point random number between 0 (inclusive) and 1 (exclusive). You apparently want a floating-point random number from 0 to z. Simply "scaling" the random by multiplying it with z should be fully sufficient and only takes a single call to math.random:

local function ARN() return math.random() * z end

This may slightly decrease randomness in the floating point part, but for small z it shouldn't be noticeable.

Your implementation currently is from 0 (exclusive) to z (inclusive). In practice this probably matters rarely, but are these the intended bounds? The scaling I have presented would be consistent with math.random, with 0 being exclusive and z being inclusive.

As for "randomness": math.random uses xoshiro256** and you're pretty much just using math.random, so you should have about the same randomness. It's just a "pseudo" and not a "secure" random though.

Also consider seeding the random using math.randomseed(os.time() os.clock()) or the like; note that the seed is global and whether you want to seed it depends on your application (you might want a fixed seed for testing purposes f.E.).

  • Related