When using random numbers in Java - java

After I imported the math class...
Math.random()
I am confused at how to make the range of the numbers. I know you can multiply, and then add/subtract, but the logic is not making sense to me, and I am also not overly sure how to make the range. Can I get some help?

If you want the range [min, max], then you can use this formula:
Math.random() * (max - min) + min

random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Make your own arrangement like if you need it below 50 multiply it by 50.

If you're trying to get a range of integers from 0 to n, then look at java.util.Random nextInt(int n)

Math.random() returns a double in between 0 and 1. So, say you wanted a number between 0 and 10:
double random = Math.random()*10;
Or maybe a range from -10 to 10:
double random = (Math.random()-0.5)*20;
Notice how I did *20 instead of 10. Subtracting 0.5 would then return a value between -0.5 and 0.5, so 0.5*20 = 10 and -0.5*20 = -10.

You have to describe you problem more. Anyway, in Java, there is class which is created specifically for working with Random numbers. Which is java.util.Random. Refer java documentation for more details. It has many methods which helps you to work with random numbers in many ways.
Some of the methods are nextInt(int limit) will give a random value between zero(inclusive) and limit(exclusive). If you need real numbers, then you have nextDouble() which will give a value between 0.0 and 1.0.

Related

How to implement a all inclusive random number function in Clojure?

I was wondering how to have inclusive random numbers in Clojure. I came up with this:
(import java.util.Random)
(def rnd
(Random.))
(defn random-float
[min max rnd]
(+ min (* (.nextDouble rnd) (- max min))))
It seems that Java only has inclusive/exclusive random functions. According the documentation:
The general contract of nextDouble is that one double value, chosen
(approximately) uniformly from the range 0.0d (inclusive) to 1.0d
(exclusive), is pseudorandomly generated and returned.
Is there a way to have an inclusive/inclusive version of this function. I was thinking about increasing the maximum value with a tiny bit (0.0000000000000001). Not sure what is the impact if I do so.
Would this work?
(random-float 0.0 1.0000000000000001 rnd)
How important is the double precision for your case?
You could use integers for everything with clojure.core's rand-int e.g:
for a number between 0-100: (rand-int 101)
for a number between 0-1000: (rand-int 1001)
etc
I'd also note that there are other Clojure rand-style functions such as random-sample and rand ; if rand-int isn't what you're looking for, still you probably won't need to fallback to Java.

Safely generate random numbers between some range in Java

How do I safely generate a random integer value in a specific range?
I know many people have asked this before, this post for example, but the method doesn't seem to be safe. Let me explain:
The 'Math' library has Math.random() which generates a random value in the range [0, 1). Using that, one can construct an algorithm like
int randomInteger = Math.floor(Math.random() * (Integer.MAX_VALUE - Integer.MIN_VALUE + 1) + Integer.MIN_VALUE)
to generate a random number between Integer.MAX_VALUE and Integer.MIN_VALUE. However, Integer.MAX_VALUE - Integer.MIN_VALUE will overflow.
The goal is not to merely generate random numbers but to generate them evenly, meaning 1 has the same probability to appear as Integer.MAX_VALUE. I know there are work-arounds to this, such as casting large values to long but then the problem again is how to generate a long integer value from Long.MIN_VALUE to Long.MAX_VALUE.
I'm also not sure about other pre-written algorithms as they can overflow too and cause the probability distribution to change. So my question is whether there is a mathematical equation that uses only integers (no casting to long anywhere) and Math.random() to generate random numbers from Integer.MIN_VALUE to Integer.MAX_VALUE. Or if anyone know any random generators that don't get overflow internally?
The 'Math' library have Math.random() which generates a random value in [0, 1) range.
So don't use Math.random() - use this:
Random r = new Random();
int i = r.nextInt();
The docs for nextInt say:
nextInt() - Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. All 2^32 possible int values are produced with (approximately) equal probability.
It appears I misread the question slightly, and you need long not int - luckily the contract is the same.
long l = r.nextLong()
This will quite literally take two ints and jam them together to make a long.
Still better might be to use
java.security.SecureRandom which is a cryptographically strong random number generator (RNG).
Random x = new Random(1000); // code running and generate values 1000
int i = x.nextInt();

Generating random unique double values in Java

I need a collection of 64-bit floating point random numbers, and they should be distinct. Is there a library routine for this, or should I manually search for duplicates?
It is actually more important to have the numbers not being closer than some very small constant \epsilon. Is there a library routine for that as well?
You may use streams for that.
double[] array = new Random().doubles()
.distinct()
.limit(500) // How many you want.
.toArray();
You can use Set collection. It won't allow insertion of unique values. Below is an example:
Set<Double> doubles = new HashSet<Double>();
Random r = new Random();
for(int i=0 ; i<100 ; i++){
doubles.add(r.nextDouble() * 100);
}
At first you need to understand, how a random-number-generator works. A sequence of positive integers, long integers, with no doubles in it, is calculated. This sequence is at least 2^31 elements long. The real doubles in the range of 0.0 ..... 1.0 are the result of a floating point division.Floating point division is never exact.
If you use this real numbers to generate integer in smaller interval, it is the quickest method,to use a random-number-generator, which gives you positive integer from that interval.
The algorithm for the Lehmer-generator is
x1 = (x0 * m) % div
x0 : the last random number,x1 the next random number. Div and m are prime numbers. m < div. The first x0 is select by the user.called seed number.
It is clear, that the x_i are smaller then div. For the other properties of good random-number-generator, there is no short proof.
My suggestion:
Write a method for a Lehmer-generator with m = 279470273 and div = 4294967291. I found these numbers on several web pages. Div = 2^32-5, so you can be sure to get a sequence of nearly 2^32 positive long integer,all different. Convert them to doubles and divide them with div as double. You get doubles in the open interval (0.0, ..... 1.0) and all these doubles are different.
The random integers are small enough, that the quotients are also different. If you use a random generator, which generate bigger integer random numbers, you can not sure, that doubles are also different, the reason are rounding errors.

Java: Math.random() Max Value (double just less than 1)

I've been a little curious about this. Math.random() gives a value in the range [0.0,1.0). So what might the largest value it can give be? In other words, what is the closest double value to 1.0 that is less than 1.0?
Java uses 64-bit IEEE-754 representation, so the closest number smaller than one is theoretically 3FEFFFFFFFFFFFFF in hexadecimal representation, which is 0 for sign, -1 for the exponent, and 1.9999999999999997 for the 52-bit significand. This equals to roughly 0.9999999999999998.
References: IEEE-754 Calculator.
The number that you want is returned by Math.nextAfter(1.0, -1.0).
The name of the function is somewhat of a misnomer. Math.nextAfter(a, 1.0) returns the least double value that is greater than a (i.e., the next value after a), and Math.nextAfter(a, -1.0) returns the greatest value that is less than a (i.e., the value before a).
Note: Another poster said, 1.0-Double.MIN_NORMAL. That's wrong. 1.0-Double.MIN_NORMAL is exactly equal to 1.0.
The smallest positive value of a double is Double.MIN_NORMAL. So, the largest number less than 1.0 is 1.0-Double.MIN_NORMAL.
Double.MIN_NORMAL is equal to 2-1022, so the answer is still extremely close to 1.0. You'd have to print the value of 1.0-Double.MIN_NORMAL to 308 decimal places before you could see anything but a 9.

Java int cast returns 0

I have the following code:
int i = (int) 0.72;
System.out.println(i);
Which yields the following output:
0
I would of imagined that the variable i should have the value of 1 (since 0.72 > 0.5 => 1), why is this not the case?
(I imagine that when casting to int, it simply cuts of the decimal digits after the comma, not taking into account of rounding up; so I'll probably have to take care of that myself?)
Correct, casting to an int will just truncate the number. You can do something like this to get the result you are after:
int i = (int)Math.round(0.72);
System.out.println(i);
This will print 1 for 0.72 and 0 for 0.28 for example.
Because when you cast a double to int, decimal part is truncated
UPDATE Math.round will give your desired output instead of Math.ceil:
System.out.println(Math.round(0.72));
// will output 1
System.out.println(Math.round(0.20));
// will output 0
You can use Math.ceil :
System.out.println(Math.ceil(0.72));
// will output 1
System.out.println(Math.ceil(0.20));
// will output 1
Casting to an int implicity drops the decimal part. That's why you get 0 because anything after the 0 is removed (in your case the 72). If you want to round then look at Math.round(...)
Explicit cast does a conversion a float/double value to an int variable (which discards the fractional part)
Java does not round-off the number like we do.It simply truncates the decimal part.
If you want to round-off the number use java.lang.Math
Casting double to int truncates the non-integer portion of the number.
To round numbers as you describe, use Math.round()
As a complete Java beginner, and just in case my experience is useful to someone, I was just making the following mistake:
int x = (int) Math.random() * 10;
... which will always set x to 0. Instead, I should've done int x = (int) (Math.random() * 10);.
Not much of a Java-know-how specific mistake, but I'll just throw this in case anyone puzzled by this stumbles upon this question.

Categories

Resources