[英]How to generate a list of random real numbers
How do I generate a list of random real numbers between a specific range, ex.如何生成特定范围之间的随机实数列表,例如。 -50 to 50?
-50 到 50? The function I wrote returns a list of only doubles.
我写的函数只返回一个双精度列表。 What I want it to return is something like this: 35, -3, 1.6, 4.5, -22.8, 10, -12, 5.2, 3.6, -8.
我希望它返回的是这样的:35、-3、1.6、4.5、-22.8、10、-12、5.2、3.6、-8。 Here's what I've tried so far...any help is appreciated!
这是我迄今为止尝试过的......任何帮助表示赞赏!
public static double [] randomArray(int A)
{
double [] randomArr = new double[A];
Random r = new Random();
for(int i = 0; i < A; i++)
{
randomArr[i] = (r.nextDouble() *(100)) - 50;
}
return randomArr;
}
You seem to be asking for a random mix of whole numbers (integers, int
or Integer
) and fractional numbers ( float
or double
, Float
or Double
). 您似乎在要求整数(整数,
int
或Integer
)和小数( float
或double
, Float
或Double
)的随机混合。 I assume you understand that a random Float
/ Double
could turn out to be a whole number with a fraction of zero, but want to dramatically increase the presence of whole numbers. 我想你明白,一个随机
Float
/ Double
可能变成是为零的小数部分的整数,但要大幅增加整数的存在。
There may be more clever ways, but I would use a random number to choose between generating the next number as an integer or as a fractional. 可能有更聪明的方法,但是我将使用随机数来选择在生成下一个整数还是小数之间进行选择。
As a random number generator, I suggest ThreadLocalRandom
as it is thread-safe by design. 作为随机数生成器,我建议使用
ThreadLocalRandom
因为它在设计上是线程安全的。
If you want to constrain the range of possible values, specify the optional origin and bound . 如果要限制可能值的范围,请指定可选的origin和bound 。 I cannot imagine why, but it appears that there is no option to specify origin/bound when generating floats, so you must use doubles.
我无法想象为什么,但是在生成浮点数时似乎没有指定源/绑定的选项,因此必须使用双精度。
If you want to truncate the fraction to a specific number of digits, see How can I truncate a double to only two decimal places in Java? 如果要将小数位数截断为特定位数,请参阅如何在Java中将双精度数截断至仅两位小数? .
。
Example code. 示例代码。
int initialCapacity = 10;
List < Number > numbers = new ArrayList <>( initialCapacity );
for ( int i = 1 ; i <= initialCapacity ; i++ )
{
int which = ThreadLocalRandom.current().nextInt( 2 ); // Produce either 0 or 1. The bound is exclusive, so we specify `2`.
switch ( which )
{
case 0:
numbers.add( ThreadLocalRandom.current().nextInt( - 50 , 50 ) );
break;
case 1:
numbers.add( ThreadLocalRandom.current().nextDouble( - 50 , 50 ) );
break;
default:
throw new IllegalStateException( "The `which` switch should be only zero or one. Message # 108d8e3f-bce7-4f0f-8dff-652940a17ba1." );
}
}
When run: 运行时:
numbers.toString(): [28.344775355282835, -36.00411659190424, 4.151429648004303, -26.898964417043725, 31, 4, 17.172537217625035, 4, 29.957510122739222, -46]
numbers.toString():[28.344775355282835,-36.00411659190424,4.151429648004303,-26.898964417043725,31,4,17.172537217625035,4,29.957510122739222,-46]
My code assumes you want approximately half and half whole and fractional numbers. 我的代码假定您需要大约一半和一半的整数和小数。 If you want a different ratio, play with the range of
which
and change the switch
to a cascading if
statement that tests for ranges of numbers. 如果要使用其他比率,请尝试使用该比率的范围
which
然后将switch
更改为级联if
语句,以测试数字范围。 For example, if you want 20% whole numbers, generate 1-10 and result of 1 & 2 produce an Integer
while 3-10 produce a Float
. 例如,如果您想要20%的整数,则生成1-10,结果1&2产生一个
Integer
而3-10产生一个Float
。 Again, there may be more clever approaches mathematically, but this approach gets the job done. 再次,在数学上可能有更聪明的方法,但是这种方法可以完成工作。
BigDecimal
The float
/ double
& Float
/ Double
types use floating-point technology. float
/ double
和Float
/ Double
类型使用浮点技术。 Floating-point trades away accuracy for speed of execution. 浮点数会牺牲精度来提高执行速度。 So some numbers cannot be represented to exactly 2 decimal places, for example.
因此,例如,某些数字不能精确表示到小数点后两位。
If you care about accuracy more than speed (such as when handling money), substitute BigDecimal
where my code used Double
. 如果您更关心准确性而不是速度(例如处理金钱时),请在我的代码使用
Double
地方替换BigDecimal
。
My code above generates a double
primitive value, while the List
stores objects. 我上面的代码生成一个
double
原始值,而List
存储对象。 Java automatically wraps the primitive as a Double
object before storing in the array. Java在存储在数组中之前会自动将原语包装为
Double
对象。 If you are unfamiliar with this trick, learn about auto-boxing . 如果您不熟悉此技巧,请了解有关自动装箱的信息 。 See Oracle Tutorial .
请参见Oracle教程 。
You can use DecimalFormat. 您可以使用DecimalFormat。
Snipplet: 片段:
import java.util.Random;
import java.text.*;
class Main {
public static void main(String[] args) {
System.out.println("Number Format Sample!");
int n = 5;
double [] randomArr = randomArray(n);
DecimalFormat format = new DecimalFormat("0.#");
for(int i = 0; i < n; i++)
{
System.out.println("randomArr item : "+format.format(randomArr[i]));
}
}
public static double [] randomArray(int A)
{
double [] randomArr = new double[A];
Random r = new Random();
for(int i = 0; i < A; i++)
{
randomArr[i] =(r.nextDouble() *(100)) - 50;
}
return randomArr;
}
}
Output: 输出:
Number Format Sample!
randomArr item : -30.8
randomArr item : -36.9
randomArr item : 44.2
randomArr item : 13.6
randomArr item : -49.1
Ref: https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html 参考: https : //docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
From Java 8+ use a stream of random numbers. 从Java 8+开始,使用随机数流。
Random r = new Random();
double[] nums =
r.doubles(20, -50., 50.).map(a -> (int) (a * 10) / 10.).toArray();
System.out.println(Arrays.toString(nums));
Generates values between -50.0..50.0 inclusive with one decimal point of precision (eg. 42.5
). 生成介于-50.0..50.0(含)之间的值,精度为小数点后一位(例如
42.5
)。 Note: Not all decimal values can be contained perfectly as a floating point value. 注意:并非所有十进制值都可以完美地包含为浮点值。
for (int i = 0; i < A; i++)
{
double value = (r.nextInt(501) / 10.0) * (r.nextBoolean() ? 1 : -1);
randomArr[i] = value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.