Randomly switch between randomly generating a whole or fractional number
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
). 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.
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.
If you want to constrain the range of possible values, specify the optional origin and 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?.
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]
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. 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
. 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. 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
.
Auto-boxing
My code above generates a double
primitive value, while the List
stores objects. Java automatically wraps the primitive as a Double
object before storing in the array. If you are unfamiliar with this trick, learn about auto-boxing. See Oracle Tutorial.