[英]Should this number be subtracted by 1 when implementing the Mersenne Twister?
I found this snippet online along with this Stackoverflow post which converts it into a TypeScript class.我在网上找到了这个片段以及这个Stackoverflow 帖子,它将它转换成一个 TypeScript 类。
I basically copy and pasted it verbatim (because I am not qualified to modify this sort of cryptographic code), but I noticed that VS Code has a little underline in the very last function:我基本上是逐字复制粘贴的(因为我没有资格修改这种加密代码),但我注意到 VS Code 在最后一个函数中有一点下划线:
/**
* generates a random number on [0,1) with 53-bit resolution
*/
nextNumber53(): number {
let a = this._nextInt32() >>> 5;
let b = this._nextInt32() >>> 6;
return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0);
}
Specifically the 9007199254740992.0
具体是9007199254740992.0
VS Code says Numeric literals with absolute values equal to 2^53 or greater are too large to be represented accurately as integers.ts(80008)
VS Code 表示Numeric literals with absolute values equal to 2^53 or greater are too large to be represented accurately as integers.ts(80008)
I notice that if I subtract that number by one and instead make it 9007199254740991.0
, then the warning goes away.我注意到,如果我将该数字减去 1 并改为9007199254740991.0
,那么警告就会消失。 But I don't necessarily want to modify the code and break it if this is indeed a significant difference.但是,如果这确实是一个显着差异,我不一定要修改代码并破坏它。
Basically, I am unsure, because while my intuition says that having a numerical overflow is bad, my intuition also says that I shouldn't try to fix cryptographic code that was posted in several places, as it is probably correct.基本上,我不确定,因为在我的直觉说,有一个数字溢出是坏的,我的直觉也说我不应该尝试修复被张贴在几个地方加密代码,因为它可能是正确的。
But is it?但是是吗? Or should this number be subtracted by one?或者这个数字应该减一吗?
9007199254740992
is the right value to use if you want Uniform values in [0,1), ie 0.0 <= x < 1.0
.如果您希望 [0,1) 中的统一值,即0.0 <= x < 1.0
,则9007199254740992
是正确的值。
This is just the automatics going awry, this value can be accurately represented by a JavaScript Number
, ie a 64bit float.这只是自动程序出错了,这个值可以用 JavaScript Number
准确表示,即 64 位浮点数。 It's just 2 53 and binary IEEE 754 floats have no trouble with numbers of this form (it would even be represented accurately with a 32bit float).它只是 2 53并且二进制 IEEE 754 浮点数对这种形式的数字没有问题(它甚至可以用 32 位浮点数准确表示)。
Using 9007199254740991
would make the range [0,1], ie 0.0 <= x <= 1.0
.使用9007199254740991
将使范围 [0,1],即0.0 <= x <= 1.0
。 Most libraries generate uniform values in [0,1) and other distributions are derived from that, but you are obviously free to do whatever is best for your application.大多数库在 [0,1) 中生成统一值,其他分布则从中派生,但您显然可以自由地为您的应用程序做任何最好的事情。
Note that the actual chance of getting the maximum value back is 2 -53 (~1e-16) so you're unlikely not actually see it in practice.请注意,获得最大值的实际机会是 2 -53 (~1e-16),因此您不太可能在实践中真正看到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.