javascript - JavaScript 中更好的随机函数

标签 javascript math random

我目前正在用 JavaScript 制作康威生命游戏复制品,我注意到函数 Math.random() 总是返回某种模式。以下是 100x100 网格中的随机结果示例:

enter image description here

有人知道如何获得更好的随机数吗?

ApplyRandom: function() {

    var $this = Evolution;

    var total = $this.Settings.grid_x * $this.Settings.grid_y;
    var range = parseInt(total * ($this.Settings.randomPercentage / 100));

    for(var i = 0; i < total; i++) {
      $this.Infos.grid[i] = false;
    }

    for(var i = 0; i < range; i++) {
      var random = Math.floor((Math.random() * total) + 1);
      $this.Infos.grid[random] = true;
    }

    $this.PrintGrid();
  },

[更新]

我在这里创建了一个jsFiddle:http://jsfiddle.net/5Xrs7/1/

[更新]

看来 Math.random() 毕竟还可以(感谢 raina77ow)。对不起各位! :(。如果您对结果感兴趣,这里是游戏的更新版本:http://jsfiddle.net/sAKFQ/

(但我认为还存在一些错误......)

最佳答案

代码中的这一行...

var position = (y * 10) + x;

...是导致这种“非随机性”的原因。确实应该是……

var position = (y * $this.Settings.grid_x) + x;

我想 10 是这个网格的原始大小,这就是它在这里的原因。但这显然是错误的:您应该根据网格的当前大小来选择您的位置。

<小时/>

作为旁注,无意冒犯,但我仍然认为 @JayC 答案中给出的算法优于您的算法。而且实现起来非常简单,只需将 ApplyRandom 函数中的两个循环更改为单个循环即可:

var bias = $this.Settings.randomPercentage / 100;
for (var i = 0; i < total; i++) {
  $this.Infos.grid[i] = Math.random() < bias;
}

通过此更改,您将不再遭受在 var random = Math.floor((Math.random() * Total) + 1); 行中重复使用相同数字的副作用,这降低了原始代码中的实际单元格填充率。

关于javascript - JavaScript 中更好的随机函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16884631/

相关文章:

javascript - WordPress 加载正确的图像尺寸

c++ - 计算 Eigen::Matrix 的 sign() 的最佳方法

random - 数字食谱 ran3 生成负数

java - 我很难在 JavaFX 中调整某些元素的大小

c# - C# 和 Java 之间的随机行为差异 : the seed

Java-随机生成矩形

python - python中的随机样本

php - php 数组中的引号到 javascript 数组

javascript - 无法使用 PHP 从 CollegeBoard 获取内容

javascript - tsconfig.json : not input were found in config file?