Why all my randoms are the same? [Answered]
so there is the code and the outputs why are they the same and how to change it?
28 Replies
the output
why am i not getting "new" random for every instance?
you are, it's just that it's happening so fast that the seed ends up being the same because you are creating a new
Random
every time. consider keeping around the Random
instance and just re-using it instead of newing it up every time.make a static
Random
and use that instead of creating a new one
also, due to Math.Round
you're not getting an even distribution of valuesRandom.Shared
winforms
.net framework 4.7.2
yeah
that doesnt happen in .Net core
@TheRanger i have other similar class
but on ints
not doubles
and works just fine
it seems Random in .Net Framework gives the same seed
happens the same with ints
but was probably not called so fast which is why you get different numbers
so how do i make static random?
the same way you define a static method
i can't get it to work
Show your attempt
@mtreit i don't know at all
What part is not clear?
@mtreit this
"this" ?
make a static Random and use that instead of creating a new one
Do you know what static means?
sth like this?
i get that there are static members
but making a static random?
No, make it a static field instead of a method
so like
Random random = 0.5?
Then have each method that needs random numbers access that field or take the Random instance as a method parameter and pass the static field as a parameter
static Random _random = new Random();
As a field of your class that contains the methods
Be aware that Random isn't thread safe though
what does that mean D:
It means if you are writing multi-threaded code you need to be careful and avoid concurrent access to instances of Random. If you aren't writing multi-threaded / concurrent code right now, don't worry about it.
okay thank you, now it works
✅ This post has been marked as answered!