loading...
markdown guide
 

I think there's some issue with seeding. By default, it seeds some constant. I tried it on 10, 100, 1000, and 1000. It gives the same number i.e 0, 1, 81, 81 and 8081 respectively no matter how many times you repeatedly run it. Docs of golang also suggest that to avoid this behavior you should seed the rand with some value which constantly changes like time.Now().UnixNano().

 

You have to set a Seed before call Intn the first time. I think the reason for this is, the random number algorithm is deterministic. For the same Seed you get for a Intn call sequence the same random number Set. I think golang has a default Seed. Because your start random number is every time 81 for 100.

here is an example how you can set the seed by a unix timestamp.

rand.Seed(time.Now().UnixNano())

Edit:

To create "real" random number for a computer is not possible.
Except perhaps when the computer is influenced by other physical processes (user input, e.g. mouse movements to generate a number) All algorithm only give the appearance of randomness. Mostly with the help of time, I think (CPU tick).
For real random numbers you can use a service like this here
random.org/

They generates randomness via atmospheric noise.

Edit2: I think it's good that the go algorithm works determistic? e.g. when you have to write a test case for code that uses random generation. You can set an own default Seed and can therefore make a prediction of the result.

 
 

Great replies. Also add the use of crypto/rand to generate a non deterministic random number! For an example check out - dev.to/human/to-the-point-generati...

Classic DEV Post from May 18 '19

Aim to Never Stop Learning

It's OK to not know everything. It's OK to be wrong.

Mohammad Quanit profile image
23 years old Mostly Self-taught Developer, Who loves working on JavaScript & AWS. I do write here on technical topics & do technical speaking for tech events,

Sore eyes?

dev.to now has dark mode.

Go to the "misc" section of your settings and select night theme ❤️