问题描述
我需要基于2个输入值X和Y生成一个伪随机数。给定相同的X和Y值,我需要得到相同的结果。结果应该在0到1之间(含0和1)。
I need to generate a pseudo-random number based on 2 input values X and Y. Given the same X and Y values I need to get the same result. The result should be between 0 and 1 inclusive.
到目前为止,我已经做到了:
So far I have this:
const int a = 0x7fffffff / 48271;
const int b = 0x7fffffff % 48397;
float rand(int x, int y) {
float seed, result;
seed = x ^ ((y << 1) & 0x2AAAAAAA) ^ ((y >> 1) & 0x33333333);
result = 48353 * (seed % a) - b * (seed / a);
return (result);
}
这给了我一个结果,但不是我想要的。我从网上看到的随机事物中整理了一下,所以不知道它是否真的有用。
It's giving me a result but not what I'm looking for. I've cobbled it together from random things I've seen on the net, so no idea if it's really any good.
推荐答案
从:
float rand(uint32_t x, uint32_t y) {
/* mix around the bits in x: */
x = x * 3266489917 + 374761393;
x = (x << 17) | (x >> 15);
/* mix around the bits in y and mix those into x: */
x += y * 3266489917;
/* Give x a good stir: */
x *= 668265263;
x ^= x >> 15;
x *= 2246822519;
x ^= x >> 13;
x *= 3266489917;
x ^= x >> 16;
/* trim the result and scale it to a float in [0,1): */
return (x & 0x00ffffff) * (1.0f / 0x1000000);
}
通常的想法是服从 x
和 y
进行各种1:1转换,并将它们混合在一起以在结果中均匀分布所有输入位。然后将结果浮点数设为[0,1)。我已经从可能的输出中排除了1.0,因为包含它可能有点儿麻烦。
The general idea is to subject x
and y
to a variety of 1:1 transforms and to mix those together to distribute all of the input bits evenly(ish) throughout the result. Then the result in floating-point to [0,1). I've excluded 1.0 from the possible outputs because including it turns out to be kind of fiddly.
与任何奇数的乘积(无符号溢出)为1:1之所以进行转换,是因为奇数均是具有2的幂的互质数( uint32_t
的范围限制)。不幸的是,乘法只允许低阶位影响高阶位。它不允许高位影响低位。为了弥补这一点,我们有一些 x ^ = x>> k
项,以将高位混合到低位。
Multiplication by any odd number, with unsigned overflow, is a 1:1 transform because odd numbers are all co-prime with powers of two (the range limit of a uint32_t
). Unfortunately multiplication only allows low order bits to affect high order bits; it doesn't allow high bits to affect low. To make up for that, we have a few x ^= x >> k
terms, to mix high bits into low positions.
这篇关于基于2个输入的伪随机数生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!