简体   繁体   English

在两个数字之间生成随机数

[英]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(); 我不想使用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 ). 这真的很容易......你只需要弄清楚哪个是最小值,两个数字之间有什么区别(让我们称之为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 ). 然后,您可以通过乘以diff来缩放Math.random值(介于01之间)(现在它的范围介于0diff之间)。 Then, if you add the minimum value, your range is between min and min + diff (which is the other value) 然后,如果添加最小值,则范围介于minmin + diff (这是另一个值)

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 如果您考虑使用负数,逻辑会稍微改变,这将适用于a >= 0 and b >= 0

If you are expecting a double result, the simplest approach is 如果您期望double结果,最简单的方法是

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. 但是,如果你想要'a'和'b'之间的随机整数有点复杂。

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. 结果不同的原因是0和1之间的随机双重将小于1,即[0.0,1.0]然而,1和6之间的随机整数通常包括1,2,3,4,5,6等。 As a decimal this is the round down of [0.0 ... 7.0) 作为小数,这是[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 . 可以在此处找到从麦克风获取数据的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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