Math.random()-不是随机的 [英] Math.random() - Not random

查看:595
本文介绍了Math.random()-不是随机的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个jQuery插件,但是有一个问题,我使用以下代码:

I created a jQuery plugin but I have a problem, I use the following code:

Math.floor(Math.random()*500)

我将结果添加到元素中, 但奇怪的是,每次的结果都是一样的.

I add the result to a element, but bizarrely the result is every time the same.

如果我在生成随机数之后的行中添加了alert(), 我得到随机值,为什么? 我想得到没有alert()随机整数的信息.但是如何?

If I add a alert() to the line after the random-number-generation, I get random values, why? I want to get without the alert() random integers. But how?

推荐答案

随机数函数是一个模拟随机的方程,但它仍然是一个函数.如果给它相同的种子,第一个答案将是相同的.

The random number function is an equation that simulates being random, but, it is still a function. If you give it the same seed the first answer will be the same.

您可以尝试更改种子,并在首次加载javascript时执行此操作,这样,如果随机数生成器具有时间成分,则它可以使用加载页面的延迟来使数字更随机化.

You could try changing the seed, and do this when the javascript is first loaded, so that if there is a time component to the random number generator, then it can use the delays of pages being loaded to randomize the numbers more.

但是,您可能想要更改种子.您可以使用Date()函数,然后获取毫秒数并将其用作种子,这可能有助于先对其进行加扰.

But, you may want to change the seed. You can use the Date() function, then get the milliseconds and use that as the seed, and that may help to scramble it up first.

我认为生成器有一个时间成分,它会随着警报而变化,因为尽管我尚未对此进行测试,但生成下一个数字时会延迟.

My thought that there is a time component to the generator is the fact that it changes with an alert, as that will delay when the next number is generated, though I haven't tested this out.

更新:

我意识到规范指出,Math.random没有参数,但是正在使用种子.

I realize the specification states that there is no parameter for Math.random, but there is a seed being used.

我来自C语言,然后来自Java语言,因此使用参数没有错误的事实使我认为它使用了它,但是现在我发现那是不正确的.

I came at this from C and then Java, so the fact that there was no error using an argument led me to think it used it, but now I see that that was incorrect.

如果您真的需要种子,那么最好的选择是编写一个随机数生成器,然后Knuth的书是最好的起点.

If you really need a seed, your best bet is to write a random number generator, and then Knuth books are the best starting point for that.

这篇关于Math.random()-不是随机的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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