Java Algorithms How to - Generate random float number within -1 and 1








Question

We would like to know how to generate random float number within -1 and 1.

Answer

import java.util.Random;
/*from   w w w .  j av  a 2s  .  c om*/
public class Main {
  public static void main(String[] args) {
    Random random = new Random();
    for (int i = 0; i < 1000000000; i++) {
      float f = random.nextFloat() * 2 - 1;
      if (Float.isNaN(f)) {
        System.out.println("NaN!");
      }
    }
  }
}