lundi 7 mars 2022

How do I increase the precision of my random float generator function?

(Yes, I've searched this up already. This is not a duplicate question.)

Here what I currently have. A quick overview of what's happening:

I first get a random float number between min and max.

Then I multiply the random value by p, round it, then divide the rounded number by p to only show precision digits after the decimal.

#include <iostream>
#include <random>

float frand(float min, float max, unsigned int precision = 2)
{
    float p = powf(10, precision);
    return std::round(((rand() / (RAND_MAX / (max - min))) + min) * p) / p;
}

int main()
{
    srand(time(NULL));
    std::cout << frand(-1, 1, 10);
    return 0;
}

Unfortunately, the precision of these random values never goes past 5 digits after the decimal. I've also tried this with doubles and it doesn't get more precise.

After some testing I found that I can increase the precision at the cost of getting a number completely out of range by storing a larger random number in a long long or using LLONG_MAX instead of RAND_MAX. It looks like I need two larger values that match each other, but I'm not certain of it.

So is there a way that this code can be changed to get the maximum precision of floats or doubles? Or is this the limit?




Aucun commentaire:

Enregistrer un commentaire