dongwuge6201 2013-10-24 13:56
浏览 49
已采纳

这个函数是否给出随机数?

Question may be off topic, but I was just wondering if this wouldn't be a nice and simple random number function. It's supposed to give a random Number from 0 to $max:

function randomNumber($max){
  ((int)(1000000000000 / microtime())) % ($max+1);
}

If I'm not missing something pretty obvious here this should work, shouldn't it? But, the next question would be: Are the numbers created here really random? When I simulate 1'000'000 dice rolls, I get something like the following:

Array
(
    [1] => 166520
    [2] => 166619
    [3] => 166522
    [4] => 167001
    [5] => 166512
    [6] => 166826
)

Why I'm asking this question is: I've read that it's not possible to create a truly random number, so I started thinking and this function seems to give quite random results, without being complicated at all. So am I missing something here?

  • 写回答

1条回答 默认 最新

  • duanbi3786 2013-10-24 14:08
    关注

    That's not pseudo-random enough to be considered acceptably random.

    Please keep in mind that even numbers generated with a random number generator aren't truly random. They're just pseudo-random enough that they can be used when a random number is required. They still follow a pattern, albeit a really complicated one.

    While it may be a simple solution, and it may appear to give you random numbers, you might find oddities in aggregated data generated specific to your application. For example, if you were generating rolls for a game like Monopoly where you generate two dice rolls at the same time, you might find a higher incidence rate for rolling doubles than is typical. I can't say that your specific algorithm would cause this specific problem. This is just an example of the type of anomalies you could encounter using your own random number generation routine.

    One thing I can say specifically is that your generated values are based on the current number of microseconds at generation time. If you generate two values within a couple of milliseconds, the results will be nearby. A typical random number generator seeds the generator with a value (usually from the current time), but from that point on each call to generate another number simply provides the next value in the random sequence started by the seed. The number you get is not dependent on the time unless you reseed the generator with each call. This element is present in your routine, though, and may also be the source of unwanted side-effects.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献