0

I'm programming a perceptron and really need to get the range from the normal NextDouble (0, 1) to (-0.5, 0.5). Problem is, I'm using an array and I'm not sure whether it is possible. Hopefully that's enough information.

Random rdm = new Random();

double[] weights = {rdm.NextDouble(), rdm.NextDouble(), rdm.NextDouble()};
Patrick
  • 13
  • 5

2 Answers2

2

Simply subtract 0.5 from your random number:

double[] weights = {
                     rdm.NextDouble() - 0.5, 
                     rdm.NextDouble() - 0.5, 
                     rdm.NextDouble() - 0.5 
                   };
Ajay
  • 18,086
  • 12
  • 59
  • 105
Mateusz Dryzek
  • 651
  • 4
  • 18
  • See also: http://stackoverflow.com/questions/3975290/produce-a-random-number-in-a-range-using-c-sharp – Rana Mar 28 '16 at 22:02
  • Just a heads up: this way you will get values between -0.5 and 0.49999 (aprox.). – Andrew Mar 28 '16 at 22:21
1

If you need a only one decimal value (my wild guess from what I have seen in Wikipedia) and to include both limits, I wouldn't use a double but just a decimal value and then do the math:

(rdm.Next(11) - 5) / 10M;

That will return any of the 11 different possible values from -0.5 to 0.5.

Or you could go the double way but with a rounding, so you can actually hit the upper limit (0.5):

Math.Round(rdm.NextDouble() - 0.5, 1);

This way is probably a tiny bit slower than my first suggestion.

Andrew
  • 7,602
  • 2
  • 34
  • 42