简体   繁体   中英

std::mt19937 gives the same random float for identical first float numbers ex(1.2, 1.5)

I have this random-float function that looks like so:

float randomFloat(float input)
{
    std::mt19937 mt;
    mt.seed(input);
    std::uniform_real_distribution<float> dt(-1,1);

    return dt(mt);
}

as you can see the function takes an input and return an output between -1 and 1

but my problem is that when I give an input float if the number to the left side of the dot is the same. example : (1.2, 1.52, 1.658, 1.01...) the random float will give the same value, (apologize for bad english)

so an input of 1.5 and another input of 1.2 will give the same return value while an input of 1.5 and another input of 2.5 will give different values. how do I fix this ?

keep in mind that I'm not trying to get a randomFloat exactly, my problem is a bit more complicated but if I can get help for this specific problem everything else will be easy to make, and the reason I'm saying this is that I don't want answers telling me to use random_device or that the mt should be seeded once... I already know, this is what I'm working on if you really want to know.

thanks!

The seed value expected is an unsigned integral type; passing a float is really just passing the truncated integer value of said float .

You can derive this from the signature of seed , which returns result_type , and from the documentation of result_type :

result_type - The integral type generated by the engine. Results are undefined if this is not an unsigned integral type.

std::mt19937 的结果类型为 std::uint_fast32_t,这也是要播种的参数类型,因此,浮点数会被截断。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM