Is it possible to return a value like 1.125155, which is a double value greater than 1?
My code:
Math.random()
Is it possible to return a value like 1.125155, which is a double value greater than 1?
My code:
Math.random()
This is not possible if you are using java.lang.Math. (Read Doc)
You can do something like this :
Random ran = new Random();
double x = ran.nextDouble() + 1
The x
is now the random number that has double
value greater than 1.
You can move the decimal place using BigDecimal like this...
Random ran = new Random();
double result = BigDecimal.valueOf(ran.nextDouble()).movePointRight(1).doubleValue()
If you don't have to convert back to double
the code will be cleaner and you'll have more control over rounding issues if you plan on using the returned value in further calculations (above I have converted back to double as this is what your OP asked for).
Math.random() returns a double from [0,1]; Therefore, to get it to return a number great than 0 you would have to do one of a couple of things
Math.random() + 1 returns an number from [0+1, 1+1] or [1,2]
Math.random() * 2 returns a number from [0*2, 1*2] or [0,2]
There is a workaround to it if you want to use two values which possibly should be random and never be same(random function sometimes give same value when executed twice), then put your values to a list and use list.shuffle() Hope this helps.