简体   繁体   中英

Generate random numbers between two numbers

public class TestSample {
    public static void main(String[] args) { 

        int a = Integer.parseInt(args[0]);
        int b = Integer.parseInt(args[1]);

        double ran = Math.random();



    }
}

I don't want to use Random r = new Random(); class. Is there any other way to generate random numbers. I am just struck with what logic could be applied to generate random numbers between two numbers.

It's really easy... you only need to figure out which is the minimum value and what is the difference between the two numbers (let's call it diff ). Then, you can scale the Math.random value (between 0 and 1 ) by multiplying by diff (now its range is between 0 and diff ). Then, if you add the minimum value, your range is between min and min + diff (which is the other value)

int min = min(a,b);
int max = max(a,b);

int diff = max - min;

int result = min + diff * Math.random();

Consider using this code:

int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
double ran = Math.random();
double random;

if(a < b)
    random = (b-a)*ran + a;
else
    random = (a-b)*ran + b;

This will work for a >= 0 and b >= 0 if you consider using negative number the logic sligtly changes

If you are expecting a double result, the simplest approach is

int a =
int b =
double result = (a-b)*Math.random() + b;

It doesn't matter which is greater as you get the same distribution.

However, if you want a random integer between 'a' and 'b' is a bit more complex.

int a = 
int b =
int result = Math.floor((Math.abs(a-b)+1) * Math.random()) + Math.min(a, b);

The reason the result is different is that a random double between 0 and 1 will be just less than 1 ie [0.0, 1.0) However a random integer between 1 and 6 usually includes 1, 2, 3, 4, 5, 6 equally. As a decimal this is the round down of [0.0 ... 7.0)

You may get white noise from your microphone, and take any number from there. After that you may take any number from the given data, and do with it what you want. The example of getting data from the microphone can be found here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM