Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

281
Visualizações
JavaScript - Difference between random function results

Is there a difference between the results of Math.floor(Math.random() * x) + 1 and Math.ceil(Math.random() * x)?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Math.random() produces floating point values in the interval [0, 1) (from zero inclusive to one exclusive). This means that there is a slight difference between the two approaches:

Math.ceil(Math.random() * x) will produce integers in the interval [0, x] (from zero inclusive to x inclusive). This is because Math.ceil(0) will return a zero. Although the chance of getting that is extremely small.

function minRandom() { return 0; }
function maxRandom() { return 0.9999999; }

const x = 10;
console.log("min:", Math.ceil(minRandom() * x));
console.log("max:", Math.ceil(maxRandom() * x));

Math.floor(Math.random() * x) + 1 will produce integers in the interval [1, x] (from one inclusive to x inclusive). This is because Math.floor(Math.random() * x) itself produces integers in the interval [0, x-1] (zero inclusive to x-1 inclusive).

function minRandom() { return 0; }
function maxRandom() { return 0.9999999; }

const x = 10;
console.log("min:", Math.floor(minRandom() * x) + 1);
console.log("max:", Math.floor(maxRandom() * x) + 1);

about 4 years ago · Juan Pablo Isaza Relatório

0

Yes, there's a difference.

There is a chance, albeit a very very small one, that the second version could unexpectedly return zero.

This happens if Math.random() itself returns exactly 0.0, which it legally can.

about 4 years ago · Juan Pablo Isaza Relatório

0

Yes, there is.

...(Math.Random() * 20) - will give results between 0 and 19.99999999999, so it actually does not goes up to 20.

...(Math.Random() * 20) + 1 - will give results between 0 and 20.99999999, which actually could possibly include 20.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda