bluebox
bluebox

Reputation: 555

.NET - How to generate random numbers in a range with a certain step size?

I'd like to generate random numbers in a range (say between 0 and 1) - but with a certain step size (say 0.05). There's a python function that does exactly that:

random.randrange ( [start,] stop [,step] )

So my problem is not how to generate random numbers in a range - instead I need a way to do this with a certain step size. How can this be done in .NET?

Upvotes: 3

Views: 20570

Answers (2)

Nianios
Nianios

Reputation: 1426

You can try something like that:

  Dim objRandom As New System.Random
  Label1.Text = Math.Round(objRandom.NextDouble() * 2, 1) / 2

So you create a random double and you round it to one digit (example: 0.8).
Then you divided it with 2 and you get what you want

Upvotes: 0

Patrick McDonald
Patrick McDonald

Reputation: 65421

You could generate a random integer between 0 and 20 and divide the result by 20

Dim rnd = New Random()
Dim nextValue = rnd.Next(21) / 20

This will give you a random number between 0 and 1 (inclusive) in 0.05 increments

Upvotes: 5

Related Questions