Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript random generate 0 or 1 integer [duplicate]

Tags:

javascript

People also ask

What JavaScript code generates a random number between 0 and 1?

Javascript creates pseudo-random numbers with the function Math. random() . This function takes no parameters and creates a random decimal number between 0 and 1. The returned value may be 0, but it will never be 1.

How can you pick randomly a float between 0 and 1 in JS?

Math. random() as is will generate a random float number between 0.0 and 1.0 . From 0 inclusive to 1 exclusive.

How do you generate a random number between 0 and 1?

The random. uniform() function is perfectly suited to generate a random number between the numbers 0 and 1, as it is utilized to return a random floating-point number between two given numbers specified as the parameters for the function.

Can you randomly return 1?

For rand() / RAND_MAX it means that 1 is actually a possible result, though because of integer division, 0 is the only other possible result.


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.


There is a +1 with Math.random, so it will always going to add 1 to the randomly generated number. You can just randomly generate a number, since Math.random will generate any floating number between 0 & 1, then use if.. else to assign 0 or 1

var y = Math.random();
if (y < 0.5)
  y = 0
else
  y= 1
console.log(y)