Reputation: 925
I'm creating a Neural Network in Java and need to create a method to generate random weights initially.
I need to create a function that returns a random double value between -1 and 1 but not sure of the logic for doing this so any help would be most appreciated.
Upvotes: 8
Views: 9687
Reputation: 198023
You can use the Random class's nextDouble() method.
Random rng = new Random();
// to get a double between -1 and 1
return rng.nextDouble() * 2 - 1; // rng.nextDouble() is between 0 and 1
Upvotes: 11
Reputation: 6608
Math.random() will give you a random double between 0 and 1. You can multiply that result by 2 and subtract 1 for a random double between -1 and 1.
Alternatively you can apply the same transformation to a call to the nextDouble() method from java.util.Random
, but this requires an explicit instance of Random
whereas that is done behind the scenes with Math.random()
.
Upvotes: 8