为什么rand()并不是真正随机的? [英] Why rand() isn't really random?

查看:485
本文介绍了为什么rand()并不是真正随机的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在图像上随机放置一些点(在太空中星星点缀一些有趣的辅助项目)

I wanted to put random points on an image (stars in space for some little fun side project)

我有这个简单的脚本.

I have this simple script.

<?php
$gd = imagecreatetruecolor(1000, 1000);
$white = imagecolorallocate($gd, 255, 255, 255);

for ($i = 0; $i < 100000; $i++) 
{
    $x = rand(1,1000);
    $y = rand(1,1000);

    imagesetpixel($gd, round($x),round($y), $white);
}

header('Content-Type: image/png');
imagepng($gd);
?>

请记住,这只是为了测试,这就是为什么我将100000放入for循环中的原因,因此它显示了我注意到的新兴模式.我们有100万个像素可以使用,仍然由X和Y随机创建此模式:

Keep in mind this is just for testing, that is why I put 100000 in for loop so it shows the pattern I noticed emerging. We have 1 million pixel to use, still random X and Y creates this pattern instead:

所以它不是随机的.我知道兰德不是真正的随机数,这就是为什么它不适用于密码学的原因.但是我找不到有关它如何工作以及如何避免这种模式的信息.

So it is far from random. I know rand is not real random, that is why it isn't good for cryptography. But I find no information about how it works and what should I do to avoid patterns like this.

推荐答案

线性同余随机数生成器(PHP rand使用的线性同余随机数生成器)将始终在x-y图上显示自相关效果.

Linear congruential random number generators (which is what PHP rand uses) will always display autocorrelation effects on an x-y plot.

使用mt_rand您将获得更好的结果.这是Mersenne Twister发生器.

You will have better results with mt_rand. This is a Mersenne Twister generator.

这篇关于为什么rand()并不是真正随机的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆