Generate random float, both bounds inclusive - java

I need to generate random real numbers in the range [-0.5, 0.5], both bounds inclusive.
I found various ways to generate similar ranges, like
-0.5 + Math.random()
But the upper bound is always exclusive, I need it inclusive as well. 0.5 must be inside the range.

One way to achieve this would be to create random int from -500 to 500 and then divide it by 1000.
int max = 500;
int min = -500;
int randomInt = rand.nextInt((max - min) + 1) + min;
float randomNum = randomInt / 1000.00f;
System.out.println(randomNum);
You can change the precision by adding and removing zeros from the integer boundaries and the divisor. (eG: create integers from -5 to +5 and divide by 10 for less precision)
A disadvantage of that solution is that it does not use the maximum precision provided by float/double data types.

I haven't seen any answer that uses bit-fiddling inside the IEEE-754 Double representation, so here's one.
Based on the observation that a rollover to a next binary exponent is the same as adding 1 to the binary representation (actually this is by design):
Double.longBitsToDouble(0x3ff0000000000000L) // 1.0
Double.longBitsToDouble(0x3ffFFFFFFFFFFFFFL) // 1.9999999999999998
Double.longBitsToDouble(0x4000000000000000L) // 2.0
I came up with this:
long l = ThreadLocalRandom.current().nextLong(0x0010000000000001L);
double r = Double.longBitsToDouble(l + 0x3ff0000000000000L) - 1.5;
This technique works only with ranges that span a binary number (1, 2, 4, 8, 0.5, 0.25, etc) but for those ranges this approach is possibly the most efficient and accurate. This example is tuned for a span of 1. For ranges that do not span a binary range, you can still use this technique to get a different span. Apply the technique to get a number in the range [0, 1] and scale the result to the desired span. This has negligible accuracy loss, and the resulting accuracy is actually identical to that of Random.nextDouble(double, double).
For other spans, execute this code to find the offset:
double span = 0.125;
if (!(span > 0.0) || (Double.doubleToLongBits(span) & 0x000FFFFFFFFFFFFFL) != 0)
throw new IllegalArgumentException("'span' is not a binary number: " + span);
if (span * 2 >= Double.MAX_VALUE)
throw new IllegalArgumentException("'span' is too large: " + span);
System.out.println("Offset: 0x" + Long.toHexString(Double.doubleToLongBits(span)));
When you plug this offset into the second line of the actual code, you get a value in the range [span, 2*span]. Subtract the span to get a value starting at 0.

You can adjust the upper bound by the minimal value (epsilon) larger than the maxium value you expect. To find the epsilon, start with any positive value and make it as small as it can get:
double min = -0.5;
double max = 0.5;
double epsilon = 1;
while (max + epsilon / 2 > max) {
epsilon /= 2;
}
Random random = ThreadLocalRandom.current();
DoubleStream randomDoubles = random.doubles(min, max + epsilon);
Edit: alternative suggested by #DodgyCodeException (results in same epsilon as above):
double min = -0.5;
double max = 0.5;
double maxPlusEpsilon = Double.longBitsToDouble(Double.doubleToLongBits(max) + 1L)
Random random = ThreadLocalRandom.current();
DoubleStream randomDoubles = random.doubles(min, maxPlusEpsilon);

Given HOW GOD SPIDERS answer, here is a ready to use function :
public static double randomFloat(double minInclusive, double maxInclusive, double precision) {
int max = (int)(maxInclusive/precision);
int min = (int)(minInclusive/precision);
Random rand = new Random();
int randomInt = rand.nextInt((max - min) + 1) + min;
double randomNum = randomInt * precision;
return randomNum;
}
then
System.out.print(randomFloat(-0.5, 0.5, 0.01));

#OH GOD SPIDERS' answer gave me an idea to develop it into an answer that gives greater precision. nextLong() gives a value between MIN_VALUE and MAX_VALUE with more than adequate precision when cast to double.
double randomNum = (rand.nextLong() / 2.0) / Long.MAX_VALUE;
Proof that bounds are inclusive:
assert (Long.MIN_VALUE/2.0)/Long.MAX_VALUE == -0.5;
assert (Long.MAX_VALUE/2.0)/Long.MAX_VALUE == 0.5;

Random.nextDouble gives a value in the range of [0, 1]. So to map that to a range of [-0.5, 0.5] you just need to subtract by 0.5.
You can use this code to get the desired output
double value = r.nextDouble() - 0.5;

Related

Android Random Numbers Issue

I am generating random numbers and I am having a equal distribution issue. The first and last numbers in the range always have half the change of getting chosen because they don't have that possibility of being rounded to on both sides.
For example, if the user chooses a min of 1 and a max of 10, 1 and 10 will have a decreased chance of getting picked compared to the others.
Here is my current code:
double num = random.nextDouble() * (max - min) + min;
String finalNum = String.format("%." + precision + "f", num);
I know I could fix this by using a nextInt() instead but the problem is that I want to keep it a double because the user selects how many decimal places there will be.
Help is appreciated.
double min = 1.0;
double max = 10.0;
double rand = r.nextDouble();
//now we add 1 for the spread (we want the number to be from 0.5 to 10.5)
double range = max - min + 1;
rand *=range;
//now we shift by an offset of min-0.5;
rand += (min -0.5);
//now we round the number
int intRand = Math.round(rand);
you can use rand (double) for displaying your precision
and use intRand (int) for your integer random.

Generate a Double in the Double domain

According to this question, to create a Double number in a given range, you can use:
Random r = new Random();
double randomValue = rangeMin + (rangeMax - rangeMin) * r.nextDouble();
I'm trying to generate a double number in the double domain [Double.MIN_VALUE, Double.MAX_VALUE] using the same code mentioned above:
package test;
import java.util.Random;
public class Main {
public static void main(String[] args) {
double lower = Double.MIN_VALUE;
double upper = Double.MAX_VALUE;
Random rand = new Random();
for (int i = 0; i < 200; i++) {
double a = lower + (upper - lower) * rand.nextDouble();
System.out.println(a);
}
}
}
However, I'm getting just positive numbers even after many iterations:
1.436326007111308E308
2.7068601271148073E307
1.266896721067985E308
8.273233207049513E306
1.3338832492644417E308
8.584898485464862E307
1.260909190772451E308
1.5511066198317899E307
1.2083062753983258E308
2.449979496663398E307
7.333729592027637E307
7.832069948910962E307
8.493365260900201E307
5.158907971928131E307
3.126231202546818E307
1.3576316635349233E308
1.0991793636673692E308
6.991662398870649E307
My question is: How to generate a double number in the double range?
The results are not what you expected, because MIN_VALUE is the smallest possible positive double value. The smallest possible double value is -Double.MAX_VALUE (note the minus sign).
But you can not simply use lower = -Double.MAX_VALUE, because then, the difference will not be representable as a double, and will overflow.
A first idea would be something like
double d = random.nextDouble() * Double.MAX_VALUE;
if (random.nextBoolean()) d = -d;
to cover the full possible range.
EDIT: A (possibly minor) aside: The proposed method should cover the negative double values as well, and should be correct in the sense that each possible value appears either in its positive or in its negative form with equal probability. However, it will not be able to return the value Double.MAX_VALUE (because the value returned by Random#nextDouble() is strictly smaller than 1.0). But based on the implementation of nextDouble, there anyhow may be double values that will never appear in the output.
Double.MIN_VALUE is the smallest positive value that you can represent as a double.
it is not the largest negative number. that would be -Double.MAX_VALUE
As I said in the comment and others have also said, MIN_VALUE is positive. But even if you use -Double.MAX_VALUE, your computation will overflow double precision when computing upper - lower because the result will be two times the maximum double! One way around this is:
val = Random.nextDouble();
return (val < 0.5) ? (-2 * val) * Double.MAX_VALUE : (2 * (val - 0.5)) * Double.MAX_VALUE;

How to generate random values between -1/2 to 1/2

I am trying to figure out a way to generate random values between 1/2 and -1/2.
I tried something as below, but not sure if this is a right way to do it....
Can someone please let me know a good way to implement this?
public static void main(String args[]) {
double Max = .5;
double Min = -0.5;
for (int i = 0; i < 10000; i++) {
double value = Min + ((Math.random()) * (Max - Min));
System.out.println(value);
}
}
Well Math.random() returns a random double between 0 and 1, so to change the range to -1/2 to 1/2, we can just subtract 1/2 (since 0 - 1/2 = -1/2 and 1 - 1/2 = 1/2):
Math.random() - 0.5
What you are doing now is more general, i.e. if you want a double between min and max the appropriate expression would be
min + Math.random() * (max - min)
In this case, plugging in min = -0.5 and max = 0.5 we have
-0.5 + Math.random() * (0.5 - -0.5)
which simplifies to
Math.random() - 0.5
I should also mention that, if you read the random() method's documentation, you will find that it returns a double greater than or equal to 0.0 and less than 1.0. This means that the expression above should produce a number in the range [-0.5, 0.5), meaning that -0.5 can potentially be returned but 0.5 cannot be.
You could just do:
Math.random() - 0.5
This is because the min of Math.random() is 0, and the max is 1. If you subtract a half, the min will be 0 - 0.5 == -0.5 and the max will be 1 - 0.5 == 0.5.
Therefore, your original code can be shortened to:
public static void main(String args[]) {
for (int i = 0; i < 10000; i++) {
double value = Math.random() - 0.5; // no need for a "double" cast,
// Math.random() returns a double
System.out.println(value);
}
}
Bear in mind that the Math.Random() class is going to return a value between 0 and 1, not including 1.
In this case, Math.Random()-0.5 will work sweetly

Java Random double in interval [-1000, 1000]

In java I have:
Random random = new Random();
double randomNum = random.nextDouble();
which creates a random number between 0 and 1. However I want a number between -1000 and 1000, how would I scale this?
Thanks
2 possibilities:
[less dense]: multiple your results by 2000, and subtract 1000
from the result. It won't be as 'dense' as possibility 2.
get a random int in range [-1000,999], and add a random double in
range [0,1].
Note that possibility 2 ensures better randomness and better 'density' of your numbers, at the cost of 2 random calls [which might be expansive, if it is an issue].
Um, maths?
double randomNum = (random.nextDouble()-0.5d) * 2000;
Random random = new Random();
double randomNum = (random.nextDouble() * 2000.0d) - 1000.0d;
Try this algorithm:
Generate a random value in the range 0 to 1.
multiply that value by 2000 (the size of the desired range).
subtract 1000 from the result of step 2 (move the value into the desired range).
This gives you a number on that range
double randomNum = (random.nextDouble() * 2000) -1000;
Here is a general function you could use to linearly rescale a number between zero and one (val01) to a different range (min..max):
public static double rescale(double val01, double min, double max) {
return val01 * (max - min) + min;
}
public static double doubleBetween(double start, double end) {
Random random = new Random();
// We need 64 bits because double have 53 bits precision, so int is too short
// We have now a value between 0 and Long.MAX_VALUE.
long value = -1L;
while (value < 0)
value = Math.abs(random.nextLong()); // Caution, Long.MIN_VALUE returns negative !
// Cast to double
double valueAsDouble = (double) value;
// Scale so that Long.MAX_VALUE is exactly 1 !
double diff = (end-start)/(double) Long.MAX_VALUE;
return start + valueAsDouble*diff;
}
This will give the correct interval including both ends with full double precision. doubles have a special -0.0 value (the negative zero) which will not be given by this routine.
Random random = new Random();
int randomNum = random.nextInt(2000) - 1000;
public static double randomInterval(double minValue,double maxValue){
Random random = new Random();
double r;
do {
r = random.nextDouble();
} while (r < minValue || r >= maxValue);
return r;
}
Example :
double a = randomInterval(-1000,1000) ;

Java divison with two integer operands not working?

For some reason my math just returns 0. The value are set, I have checked.
int currentSize = 4079;
int totalSize = 500802;
int percentage = ((currentSize/totalSize) * 100);
progdialog.setProgress(percentage);
Percentage always equals percentage.
Why?
The problem, as other have pointed out, is integer division will turn anything less than 1 to zero. This happens before multiplying by 100. You can change the order of operations to get something better:
int percentage = currentSize * 100 / totalSize;
If you are concerned about rounding, you can use
int percentage = (currentSize * 100 + (totalSize >> 1)) / totalSize;
These avoid the expense of working with double or float values.
you are using 'int's for currentSize and totalSize which results in integer division which removes the fractional part, yielding 0. hence the percentage is always 0.
change it to float percentage = (((float)currentSize/totalSize) * 100); and things will be fine
I assume currentSize and totalSize are int.
currentSize = 4079;
totalSize = 500802;
If they are, then currentSize/totalSize is an integer division. The result will have no fractional part (the fractional part is removed, no round up). Therefore the result is 0.
If one of the operand is double, the result of division will have fraction. Therefore, I cast one integer operand to double.
(double) currentSize
After the calculation, if you want the result to store in int, you have to cast (convert double to int; remove fractional part).
int percentage = (int) ((double) currentSize ...
The whole code is:
int currentSize = 3;
int totalSize = 100;
int percentage = (int) ((double) currentSize / totalSize * 100);
System.out.println(percentage);
If currentSize and totalSize are integers, this calculation will do integer division, which will truncate your fraction down to 0. Use doubles.
Change your code to this:
double percentage = ((double)(currentSize/totalSize) * 100);
progdialog.setProgress(percentage);
Hope it will help yout. :)
Because the result of your calculation is a double with value less than 1. You put it in an integer so it truncates everything behind the decimal separator, resulting in zero. Try storing the value in a double instead.
double occupancyRate = 0.0;
int occupiedRoomsTotal = 12;
int totalRooms = 20;
occupancyRate = (((double) occupiedRoomsTotal / totalRooms)) * 100;
DecimalFormat df2 = new DecimalFormat("#.##");
System.out.println("Occupancy Rate = " + df2.format(occupancyRate) + "%");
Java Division of integers yields zero if both numerator and denominator are both integers and the result is less than 1.
Fix:
Make either of the operands to be floating number or double
e.g. int x = 1;
double y = 3.0;
x/y gives 0.333333
where as 1/3 results in 0.

Categories

Resources