我想设计一个大多数时候返回 true
但理论上可能返回 false
的函数。
到目前为止,我所想出的是(由于一些困惑而添加了评论):
function true(seed) {
// Poop, you can't `seed` Math.random()!
return Math.random() !== Math.random();
}
// but if I had that seed, and Math.random() was seedable,
// I could make this function return false.
但是,这会遇到一些限制。
Math.random()
的实现是 not seedable因此,连续两次调用随机数生成器(没有其他熵)永远不会两次返回相同的数字。Math.random()
将返回 0.0000000000000000 到 0.9999999999999999 之间的值,即 16 位精度。因此,根据二项式分布,真不真的概率是 (1/9999999999999999)^2。或 1.0 e-32。
我试图构建的东西只会以 1/某个越来越大的整数的概率返回false
。这纯粹是一个思想实验。空间和时间没有限制,尽管如果您的答案也考虑到了这一点,那么这是一个奖励。
编辑:我想,这是提出这个问题的另一种方式。
看看这个笨蛋。 https://plnkr.co/edit/C8lTSy1fWrbXRCR9i1zY?p=preview
<script src="//cdnjs.cloudflare.com/ajax/libs/seedrandom/2.4.0/seedrandom.min.js"></script>
function f(seed) {
Math.seedrandom(seed);
return 0.7781282080210712 === Math.random();
}
console.log(f()); // Behaves as expected
console.log(f(Math.random())); // Pretty much everything returns false
function t(seed) {
Math.seedrandom(seed);
return 0.7781282080210712 !== Math.random();
}
console.log(t()); // Returns true.
console.log(t(Math.random())); // All is well with the world.
// But, if you have the right seed!
console.log(f('Udia')); // Holy shit, this returned true!
console.log(t('Udia')); // Holy shit, this returned false!
编写返回true
的函数最有趣的方法是什么?它可以永远运行,占用尽可能多的空间等等。但它必须返回true
。 (并且返回 false
的概率最小。)
最佳答案
用随机数据填充任意大小的缓冲区,然后比较它们。
未经测试,但尝试这样的事情:
const length = 32768;
let values = [
new Uint8Array(length),
new Uint8Array(length)
];
window.crypto.getRandomValues(values[0]);
window.crypto.getRandomValues(values[1]);
let i;
for (i=0; i<length; i++) {
if (values[0][i] === values[1][i]) {
break;
}
}
if (i === length-1) {
console.log('The (nearly) impossible has occurred!');
}
关于javascript - 如何在 JavaScript 中表示最小的可能性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39114657/