Hi I'm trying to create a random number generator with float values ranging from -1 to 1 i.e.. [-1,1]. The only problem is I can only find methods that do it from [0,1].

Can anyone help me with this? Here is what I have so far....

Random r = new Random();
    
    for(int counter=1; counter<=10;counter++){
    	number = r.next.Float()
    	system.out.println(number + " ");
   	}

Recommended Answers

All 2 Replies

Multiply by 2, subtract 1.

Some error in your code:
line 5 should be System.out.println(...)
line 4 should be float number = r.nextFloat();
If the range of current random is [0,1] then

[B]float[/B]	number = -1 + 2*r.nextFloat();

the random number varies in the range of [-1,1]

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.