短字符串中的随机字符 - 随机性会受到影响吗?
如果我有一个非常短的字符串,比如说(JavaScript):
var = "abcd";
并且我想从中获取一个随机字符,我可以使用:
var random_char = str.charAt( Math.floor(Math.random() * str.length) );
现在Math.floor(Math.random()* str.length)返回 [0..3]
范围内的随机数。
是否可以通过乘以字符串来增加返回字符的感知随机性,即通过有效地增加随机数的范围?
var = "abcdabcdabcdabcdabcdabcd";
If I have a very short string, say (JavaScript):
var = "abcd";
and I want to get a random character from it, I could use:
var random_char = str.charAt( Math.floor(Math.random() * str.length) );
Now Math.floor(Math.random() * str.length)
returns a random number in the range [0..3]
.
Can the perceived randomness of the returned character be increased by multiplying the string, i.e. by effectively increasing the range of the random numbers?
var = "abcdabcdabcdabcdabcdabcd";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那不会改变任何事情。
Math.random()
返回[0..1)
之间的伪随机值。假设随机数生成器质量良好,无论将其范围映射到abc
还是abcabcabc
都没有什么区别。如果
Math.random()
返回 质量非常低的随机数(即人类只需通过查看数字序列就可以发现它们背后的逻辑),您的策略将是确实增加了感知的“随机性”。但这并不重要,因为 JavaScript 运行时通常不是由猴子编写的。That won't change anything.
Math.random()
returns a pseudo-random value between in[0..1)
. Assuming the random number generator is of good quality, it won't make a difference whether you map its range toabc
or toabcabcabc
.If
Math.random()
returned random numbers of very low quality (i.e. a human being could spot the logic behind them just by looking at the number sequence), your strategy would indeed increase the perceived 'randomness'. But that's not relevant since JavaScript runtimes are typically not written by monkeys.我会说不。获得 a、b、c 或 d 的概率仍然是 25%。
I would say no. It still is a 25% probability for getting a, b, c or d.
不,不能。更糟糕的是,您将在 12.5% 的情况下收到错误,因为
Math.round
会将值从 3.5 舍入到 3.999999,最多为 4。No, it cannot. Worse yet, you will get an error 12.5% of the time, as
Math.round
will round values from 3.5 to 3.999999 up to 4.