将“__m256 with random-bits”转换为 [0, 1] 范围的浮点值

Kar*_*ari 5 c++ random floating-point simd avx

我有一个__m256包含随机位的值。

我想,以“解释”,就得到另一个__m256保存float 在值均匀 [0.0f, 1.0f]范围。

计划使用:

__m256 randomBits = /* generated random bits, uniformly distribution */;
__m256 invFloatRange =  _mm256_set1_ps( numeric_limits<float>::min() ); //min is a smallest increment of float precision

__m256 float01 =  _mm256_mul(randomBits, invFloatRange);
//float01 is now ready to be used
Run Code Online (Sandbox Code Playgroud)

问题 1:

但是,这会在非常罕见的情况下导致问题,其中randomBits所有位都为 1,因此是 NAN?

我能做些什么来保护自己免受这种伤害?

我希望float01永远是一个可用的数字

问题2:

使用上述方法获得后,[0 到 1] 范围会保持一致吗?我知道 float 在不同幅度下具有不同的精度

Kar*_*ari 3

正如 @Soonts 所指出的,浮点数可以在 [0, 1] 范围内统一创建:

/sf/answers/3841174781/

我最终使用了下面的答案:

/sf/answers/3842521721/

//converts __m256i values into __m256 values, that contains floats in [0,1] range.
///sf/answers/3842521721/
inline void int_rand_int_toFloat01( const __m256i* m256i_vals,  
                                          __m256* m256f_vals){ //<-- stores here.
    const static __m256 c =  _mm256_set1_ps(0x1.0p-24f); // or (1.0f / (uint32_t(1) << 24));

    __m256i* rnd =   ((__m256i*)m256i_vals);
    __m256* output =  ((__m256*)m256f_vals);

    // remember that '_mm256_cvtepi32_ps' will convert 32-bit ints into a 32-bit floats
    __m256 converted =  _mm256_cvtepi32_ps(_mm256_srli_epi32(*rnd, 8));
             *output =  _mm256_mul_ps( converted, c);
}
Run Code Online (Sandbox Code Playgroud)