Math.Random, Only Generating a 0

math.random, only generating a 0?

You are using Math.random() which states

Returns a double value with a positive sign, greater than or
equal to 0.0 and less than 1.0.

You are casting the result to an int, which returns the integer part of the value, thus 0.

Then 1 + 0 - 1 = 0.

Consider using java.util.Random

Random rand = new Random();
System.out.println(rand.nextInt(3) + 1);

math.random always give 0 result

Math.random() returns a double value between 0 (inclusive) and 1 (exclusive). It does not return an integer value. Therefore, when you take the number produced by Math.random() modulo 10, it returns the same double value. The final cast to int makes that value always 0.

Run the following code to see for yourself:

double random = Math.random();
System.out.println(random); // for example 0.5486395326203879
System.out.println(random % 10); // still 0.5486395326203879
System.out.println((int) (random % 10)); // outputs 0

What you really want is to use a Random object and use Random.nextInt(bound). To have a random integer between 0 and 9, you can use:

Random random = new Random();
int value = random.nextInt(10);

Java Math.random returning 0?

Try:
Min + (int)(Math.random() * ((Max - Min) + 1)). Output should be a number between 1 and 3.
Fill in 1 for min and 3 for max. That's it. The number range should be then: [1,3] which means that 1 AND 3 is included.

Here another proposal:

int number = 1 + (int)(Math.random() * ((3 - 1) + 1));
System.out.println(number);
//alternative way:
// return number;

JavaScript random generate 0 or 1 integer

You can use Math.round(Math.random()). If Math.random() generates a number less than 0.5 the result will be 0 otherwise it should be 1.

Can Java's random function be zero?

According to the documentation, "Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0." This means it can be zero.

As Hank wrote, it is exclusive on the upper boundary (can never be 1), so maybe that's where your confusion comes from :-).

Generating random whole numbers in JavaScript in a specific range

There are some examples on the Mozilla Developer Network page:

/**
* Returns a random number between min (inclusive) and max (exclusive)
*/
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}

/**
* Returns a random integer between min (inclusive) and max (inclusive).
* The value is no lower than min (or the next integer greater than min
* if min isn't an integer) and no greater than max (or the next integer
* lower than max if max isn't an integer).
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}

Here's the logic behind it. It's a simple rule of three:

Math.random() returns a Number between 0 (inclusive) and 1 (exclusive). So we have an interval like this:

[0 .................................... 1)

Now, we'd like a number between min (inclusive) and max (exclusive):

[0 .................................... 1)
[min .................................. max)

We can use the Math.random to get the correspondent in the [min, max) interval. But, first we should factor a little bit the problem by subtracting min from the second interval:

[0 .................................... 1)
[min - min ............................ max - min)

This gives:

[0 .................................... 1)
[0 .................................... max - min)

We may now apply Math.random and then calculate the correspondent. Let's choose a random number:

                Math.random()
|
[0 .................................... 1)
[0 .................................... max - min)
|
x (what we need)

So, in order to find x, we would do:

x = Math.random() * (max - min);

Don't forget to add min back, so that we get a number in the [min, max) interval:

x = Math.random() * (max - min) + min;

That was the first function from MDN. The second one, returns an integer between min and max, both inclusive.

Now for getting integers, you could use round, ceil or floor.

You could use Math.round(Math.random() * (max - min)) + min, this however gives a non-even distribution. Both, min and max only have approximately half the chance to roll:

min...min+0.5...min+1...min+1.5   ...    max-0.5....max
└───┬───┘└────────┬───────┘└───── ... ─────┘└───┬──┘ ← Math.round()
min min+1 max

With max excluded from the interval, it has an even less chance to roll than min.

With Math.floor(Math.random() * (max - min +1)) + min you have a perfectly even distribution.

min.... min+1... min+2 ... max-1... max.... max+1 (is excluded from interval)
| | | | | |
└───┬───┘└───┬───┘└─── ... ┘└───┬───┘└───┬───┘ ← Math.floor()
min min+1 max-1 max

You can't use ceil() and -1 in that equation because max now had a slightly less chance to roll, but you can roll the (unwanted) min-1 result too.

What are the chances of Math.random returning 0?

JavaScript is a dialect of ECMAScript. The ECMAScript-262 standard fails to specify Math.random precisely. The relevant clause says:

Math.random ( )

Returns a Number value with positive sign, greater than or equal to +0/sub> but strictly less than 1/sub>, chosen randomly or pseudo randomly with approximately uniform distribution over that range, using an implementation-defined algorithm or strategy. This function takes no arguments.

Each Math.random function created for distinct realms must produce a distinct sequence of values from successive calls.

In the absence of a complete specification, no definitive statement can be made about the probability of Math.random returning zero. Each ECMAScript implementation may choose a different algorithm and need not provide a truly uniform distribution.

ECMAScript uses the IEEE-754 basic 64-bit binary floating-point format for its Number type. In this format, the significand (fraction portion) of the number has 53 bits. Every floating-point number has the form sf • 2e, where s (for sign) is +1 or −1, f (for fraction) is the significand and is an integer in [0, 253), and e (for exponent) is an integer in [−1074, 971]. The number is said to be normalized if the high bit of f is set (so f is in [252, 253)). Since negative numbers are not a concern in this answer, let s be implicitly +1 for the rest of this answer.

One issue with distributing random numbers in [0, 1) is that the representable values are not evenly spaced. There are 252 representable values in [½, 1)—all those with f in [252, 253) and e = −53. And there are the same number of values in [¼, ½)—all those with f in [252, 253) and e = −54. Since there are the same number of numbers in this interval but the interval is half as long, the numbers are more closely spaced. Similarly, in [⅛, ¼), the spacing halves again. This continues until the exponent reaches −1074, at which point the normal numbers end with f = 252. The numbers smaller than that are said to be subnormal (or zero), with f in [0, 252) and e = −1074, and they are evenly spaced.

One choice about how to distribute the numbers for Math.random is to use only the set of evenly spaced numbers f • 2−53 for f in [0, 253). This uses all the representable values in [½, 1), but only half the values in [¼, ½), one-fourth the values in [⅛, ¼), and so on. This is simple and avoids some oddities in the distribution. If implemented correctly, the probability zero is produced is one in 253.

Another choice is to use all the representable values in [0, 1), each with probability proportional to the distance from it to the next higher representable value. Thus, each representable number in [½, 1) would be chosen with probability 1/253, each representable number in [¼, ½) would be chosen with probability 1/254, each representable number in [⅛, ¼) would be chosen with probability 1/255, and so on. This distribution approximates a uniform distribution on the reals and provides finer precision where the floating-point format is finer. If implemented correctly, the probability zero is produced is one in 21074.

Another choice is to use all the representable values in [0, 1), each with probability proportional to the length of the segment in which the representable value is the nearest representable value of all the real numbers in the segment. I will omit discussion of some details of this distribution except to say it mimics the results one would get by choosing a real number with uniform distribution and then rounding it to a representable value using the round-to-nearest-ties-to-even rule. If implemented correctly, the probability zero is produced is one in 21075. (One problem with this distribution is that a uniform distribution over the reals in [0, 1) will sometimes produce a number so close to 1 that rounding produces 1. This then requires either that Math.random be allowed to return 1 or that the distribution be fudged in some way, perhaps by returning the next lower representable value instead of 1.)

I will note that the ECMAScript specification is sufficiently lax that one might assert that Math.random may distribute the numbers with equal probability for each representable value, ignoring the spacing between them. This would not mimic a uniform distribution over the real numbers at all, and I expect very few people would favor it. However, if implemented, the probability zero is returned is one in 1021 • 252, because there are 252 normalized numbers with exponents from −53 to −1074 (1020 values of e), and 252 subnormal or zero numbers.



Related Topics



Leave a reply



Submit