How to get any number in [0,1] through Math.random?

/ / [0,1)
Math.random ()
/ / (0,1]
(Math.random ()-1) *-1
/ / (0,1)
(Math.random () *-1 + Math.random () + 1) / 2
/ / [0,1]
how to get the expression?

Sep.11,2021

can think differently and do it according to the number of decimal places you need to keep.
for example, you need to keep two decimal places, that is, 0.00-1.00, remove the decimal point, that is, 0-100, then you can generate a number of 0-100, and then divide by 100.


the way you write (0,1), not all numbers with uneven probability
can be generated by Math.random. It is recommended to learn how computers express floating-point numbers
. I don't know if you really have this need, or do you come up with this idea to ask questions?


function r() {
  var num = Math.random() * 1.1
  if (num > 1) {
    return r()
  }
  return num
}

console.log(r())

if absolute averaging is not required, the following algorithm should be considered:

 

your way of thinking is impossible.

(who stepped on my answer, you can go, you give me a reason to go first. Can you do it according to the idea of the landlord?

Menu