JavaScript中更好的随机函数 [英] Better random function in JavaScript
问题描述
我目前正在用JavaScript复制Conway的生活游戏,并且我注意到函数Math.random()总是返回某种模式.以下是100x100网格中随机结果的示例:
I'm currently making a Conway's Game of Life reproduction in JavaScript and I've noticed that the function Math.random() is always returning a certain pattern. Here's a sample of a randomized result in a 100x100 grid:
有人知道如何获得更好的随机数吗?
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/
I've created a jsFiddle here: http://jsfiddle.net/5Xrs7/1/
[更新]
看来Math.random()毕竟还可以(感谢raina77ow).抱歉! :(.如果您对结果感兴趣,请参见以下游戏的更新版本: http://jsfiddle.net/sAKFQ/
It seems that Math.random() was OK after all (thanks raina77ow). Sorry folks! :(. If you are interested by the result, here's an updated version of the game: http://jsfiddle.net/sAKFQ/
(但是我认为还有一些错误……)
(But I think there's some bugs left...)
推荐答案
代码中的这一行...
This line in your code...
var position = (y * 10) + x;
...是导致这种非随机性"的原因.真的应该...
... is what's causing this 'non-randomness'. It really should be...
var position = (y * $this.Settings.grid_x) + x;
我想10
是此网格的原始大小,这就是为什么它在这里.但这显然是错误的:您应该根据当前网格的大小选择位置.
I suppose 10
was the original size of this grid, that's why it's here. But that's clearly wrong: you should choose your position based on the current size of the grid.
作为附带说明,没有违法行为,但我仍然认为@JayC答案中给出的算法优于您的算法.而且很容易实现,只需将ApplyRandom
函数中的两个循环更改为一个循环即可:
As a sidenote, no offence, but I still consider the algorithm given in @JayC answer to be superior to yours. And it's quite easy to implement, just change two loops in ApplyRandom
function to a single one:
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);
行中重复使用相同数字的副作用,从而降低了原始代码中的实际单元格填充率.
With this change, you will no longer suffer from the side effect of reusing the same numbers in var random = Math.floor((Math.random() * total) + 1);
line, which lowered the actual cell fillrate in your original code.
这篇关于JavaScript中更好的随机函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!