【问题标题】:Generate random number from 0 to 1 [duplicate]生成从0到1的随机数[重复]
【发布时间】:2017-05-28 14:17:45
【问题描述】:

如何计算 0 和 1 之间的随机数? 当我有 Math.random() 它返回 0-0.9999999

我没有找到任何解决方案。

编辑: 我认为它可能是这样的:

const precision = 1000
let c = 0
let min = 2
let max = -2

while(c !== 20000){
   c++;
   let r = (Math.round(Math.random()*precision)/precision)/0.9999999999999;
   r = Math.round(r*precision)/precision
   max = Math.max(r, max)
   min = Math.min(r, min)
 }
console.log('max:', max, 'min:', min)

【问题讨论】:

  • 你能告诉我们你尝试了什么吗?
  • 从随机浮点数中得到任何特定数字的概率基本上为零。因此,即使您包含 1,您也永远不会得到它。
  • 1 - Math.random() 试试这个
  • @V 但是你不能得到零

标签: javascript algorithm random numbers


【解决方案1】:

这就是你要找的东西。

Examples #4 on the Mozilla Developer Network

【讨论】:

  • 但这是针对整数的
  • 如果排除Math.floor,它将是Math.random() * (max - min + 1) + min; ... ...或Math.random() * 1
  • @Jaromanda 乘以 1 有何变化?
  • 它没有 - 我只是指出该代码将如何在 float 范围为 0...1 的情况下“工作”......换句话说,它没有区别
猜你喜欢
  • 2017-10-22
  • 2017-12-21
  • 2014-04-11
  • 1970-01-01
  • 2013-01-02
  • 2012-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多