javascript - Math.round(Math.random()) 组合似乎在我的 javascript 程序中生成了太多 0

标签 javascript math

我正在尝试制作一个非常简单的脚本来生成一个二维数组,其中每个第 n 个数组不包含它自己的索引作为元素,但包含随机数量的其他随机索引值作为其元素,并且不能为空。以下是我为尝试实现此目的而编写的一些代码:

totElList = []
numEls = 1000

for (i=0;i<numEls;i++) {
    totElList[i] = []
    for (j=0;j<numEls;j++) {
        totElList[i][j] = j
    }
}

for (i in totElList) {
    totsplice = Math.round(Math.random()*(numEls-1))
    totElList[i].splice(i,1)
    for (j=0;j<totsplice;j++) {
        rand = Math.round(Math.random()*totElList[i].length)
        while (typeof(totElList[i][rand]) === undefined) {rand = Math.round(Math.random()*totElList[i].length)}
        totElList[i].splice(rand,1)
    }
}

问题是当我运行这个时,totElList 数组似乎比任何其他数字包含更多的 0,即使我假设元素会被随机删除。我做了一个测试来证实这一点。对于给定的 numEls,0 的数量始终是所有可能值中的最大值。我猜这与 Math.random() 和 Math.round() 的工作有关,但我不确定。有人可以给我一些见解吗?谢谢。

最佳答案

而不是 Math.round ,取Math.floor这对于索引来说效果更好,因为它是从零开始的。

Example with one digit and a factor of 2 as index for an array with length of 2.

As you see, the second half index is moved to the next index of every number, which results into a wrong index and with the greatest random value, you get an index outside of the wanted length.

value  round  floor  comment for round
-----  -----  -----  -----------------
 0.0     0      0
 0.1     0      0
 0.2     0      0
 0.3     0      0
 0.4     0      0
 0.5     1      0    wrong index
 0.6     1      0    wrong index
 0.7     1      0    wrong index
 0.8     1      0    wrong index
 0.9     1      0    wrong index
 1.0     1      1
 1.1     1      1
 1.2     1      1
 1.3     1      1
 1.4     1      1
 1.5     2      1    wrong index
 1.6     2      1    wrong index
 1.7     2      1    wrong index
 1.8     2      1    wrong index
 1.9     2      1    wrong index

关于javascript - Math.round(Math.random()) 组合似乎在我的 javascript 程序中生成了太多 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54126536/

相关文章:

javascript - 获取 jQuery 下拉列表以优雅地加载和删除

javascript - 如何拆分带有小计前缀的字符串

math - 将平行(相似)多段线分组在一起

java - 在围绕点的周期性圆形路径上移动对象

c - C 编程中函数的泰勒展开式 f(x)=sin(x)+cos(x) 存在输出错误。有什么建议么?

javascript - NodeJS 中未提供回调模式

javascript - 基于查找值求和二维数组中的值 - Javascript

javascript - 在同一个列表上使用多个灯箱会导致问题

java - 如果我们知道距离 x1, y1, y2 则计算 x2

java - 总结时四舍五入到小数点后 2 位