用随机位转换"__m256"转换为[0,1]范围的float值 [英] Convert "__m256 with random-bits" into float values of [0, 1] range

查看:75
本文介绍了用随机位转换"__m256"转换为[0,1]范围的float值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 __ m256 值,其中包含随机位.

I have a __m256 value that holds random bits.

我想解释"它,以获得另一个保存 float __ m256 统一 [0.0f,1.0f] 范围内的值.

I would like to to "interpret" it, to obtain another __m256 that holds float values in a uniform [0.0f, 1.0f] range.

计划使用以下方法:

__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

问题1:

但是,在 randomBits 的所有位均为1且因此为NAN的极少数情况下,这会引起问题吗?

However, will this cause a problem in very rare cases where randomBits has all bits as 1 and is therefore NAN?

我该怎么做才能保护自己免受这种伤害?

What can I do to protect myself from this?

我希望 float01 始终是可用的数字

I want the float01 to always be a usable number

问题2:

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

Will the [0 to 1] range remain uniform after I obtain it using the above approach? I know float has varying precision at different magnitudes

推荐答案

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

As @Soonts has pointed out, floats can be created uniformly in [0, 1] range:

https://stackoverflow.com/a/54873925/9007125

我最终使用以下答案:

https://stackoverflow.com/a/54893167/9007125

//converts __m256i values into __m256 values, that contains floats in [0,1] range.
//https://stackoverflow.com/a/54893167/9007125
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);
}

这篇关于用随机位转换"__m256"转换为[0,1]范围的float值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆