0

I've written the following code to create a random number between 0.0 and 10.0.

const minRand = 0 const maxRand = 10 v := minRand + rand.Float64()*(maxRand-minRand) 

However, I would like to set the granularity to 0.05, so having all the digits as the least significant decimal should not be allowed, only 0 and 5 should be allowed, e.g.:

  • the value 7.73 is NOT VALID,
  • the values 7.7 and 7.75 ARE VALID.

How can I produce such numbers in Go?

0

2 Answers 2

4

You can divide with the granularity, get a pseudo random integer and then multiply with the granularity to scale the result down.

const minRand = 8 const maxRand = 10 v := float64(rand.Intn((maxRand-minRand)/0.05))*0.05 + minRand fmt.Printf("%.2f\n", v) 

This will print:

8.05 8.35 8.35 8.95 8.05 9.90 .... 

If you don't want to get the same sequence every time rand.Seed(time.Now().UTC().UnixNano()).

From the docs

Seed uses the provided seed value to initialize the default Source to a deterministic state. If Seed is not called, the generator behaves as if seeded by Seed(1). Seed values that have the same remainder when divided by 2^31-1 generate the same pseudo-random sequence. Seed, unlike the Rand.Seed method, is safe for concurrent use.

Sign up to request clarification or add additional context in comments.

4 Comments

Good answer! Last line is wrong though - it's a PRNG whether you seed it or not.
That is working, could you please add the lower bound as well? Thanks @georgeok
Why do you need the lower limit? If it's zero you don't need it. rand.Intn will always return a positive number.
Consider minRand being an arbitrary number, so the solution is general.
1

With lower bounds

const minRand = 0 const maxRand = 10 const stepRand = 0.05 v := float64(rand.Intn((maxRand-minRand)/stepRand))*stepRand + minRand fmt.Printf("%.2f\n", v) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.