Hello, go devs I am learning golang and I am using the Math/Rand
package. I am curious why I am getting the same result on:
// always returning 81
rand.Intn(100)
Does anybody have knowledge about it?
Hello, go devs I am learning golang and I am using the Math/Rand
package. I am curious why I am getting the same result on:
// always returning 81
rand.Intn(100)
Does anybody have knowledge about it?
For further actions, you may consider blocking this person and/or reporting abuse
Muhammad Farooq -
r0psteev -
Erin A Olinick -
Maxime Guilbert -
Once suspended, mquanit will not be able to comment or publish posts until their suspension is removed.
Once unsuspended, mquanit will be able to comment and publish posts again.
Once unpublished, all posts by mquanit will become hidden and only accessible to themselves.
If mquanit is not suspended, they can still re-publish their posts from their dashboard.
Once unpublished, this post will become invisible to the public and only accessible to Mohammad Quanit.
They can still re-publish the post if they are not suspended.
Thanks for keeping DEV Community safe. Here is what you can do to flag mquanit:
Unflagging mquanit will restore default visibility to their posts.
Top comments (4)
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.
now it makes sense to me. Thank you
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...