Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a random float value between two floats?

Tags:

java

random

The desired output is a random float between two floats. This is the way I did it but this method doesn't work for negative floats like: random float between -1f and -30f since the bound has to be positive and I get IllegalArgumentException. It also looks pretty complicated...if you have an easier approach that would be lovely. Cheers!

unitsConsumed = rnd.nextInt(Math.round(maxUnitsConsumed-minUnitsConsumed))+minUnitsConsumed;

Where rnd is an instance of Random.

like image 458
Ryk Avatar asked Feb 03 '26 23:02

Ryk


2 Answers

You can achieve this by using the code below where min is your minimum value and max is your maximum value:

float random= rnd.nextFloat() * (max - min) + min;
like image 123
IbzDawg Avatar answered Feb 06 '26 13:02

IbzDawg


Try with

public static void main(String[] args) {
    Random rand = new Random();

    float result = rand.nextFloat() * (-1f - (-30f)) + (-30f);

    System.out.println(result);
}
like image 28
Centos Avatar answered Feb 06 '26 12:02

Centos