Reputation: 35
I need to fill an array with random numbers but the the numbers can only go to the tenths place. Is there a way to do that with Math.random? Here is what I have for my Math.random
:
double[] array = new double[size];
for (int i = 0; i < array.length; i++) {
double num = ((Math.random() * 10000.0) + 0.0);
array[i] = num;
}
return array;
Upvotes: 0
Views: 169
Reputation: 533530
If you want random number with one decimal place you can use
int size = 20;
double[] array = new double[size];
Random rand = new Random();
for (int i = 0; i < size; i++)
array[i] = rand.nextInt(10_000 * 10) / 10.0;
System.out.println(Arrays.toString(array));
prints
[8773.3, 6305.2, 2758.4, 7872.7, 4648.9, 3565.2, 9546.4, 7533.1, 2369.7, 3218.0, 9960.2, 7418.0, 8149.3, 8813.4, 638.5, 8178.9, 2831.2, 4758.7, 8238.2, 6409.1]
Note: while double
has a representation error, the Double.toString() is written to display the shortest decimal which would have that representation so you don't see any error (nor will you for an number for at least up to 100 trillion for one decimal place)
Note2: this is why you must do a (x * N) / (double) N
as it avoid cumulated errors. e.g. if you do
double y = x * 0.1
and
double y = x / 10.0;
this does not always produce the same result. This is because 0.1
cannot be represented accurately and when you use it in an operation, you compound this error. If you use 10.0
, it can be represented without error, so the error in the result will be small enough that when you call Double.toString()
you will get the expected result.
Upvotes: 1