c++ - How to enumerate all floating point values in between min and max -


for efficient random number generator unique floating point values i'd know more floating point values. i'm going split question in 2 parts.

  1. how find out how many floats lie in between min , max (including both)?

i'm looking implementation of method:

size_t numoffloats(const float min, const float max); 

which considers possible float values given maximum precision of data type.

  1. how enumerate possible float values in between min , max (including both)?

i'm looking implementation of method:

vector<float> enumallfloats(const float min, const float max); 

the size of vector returned shall equal return value of method first question.

c++11 allowed if required.

you can use ieee754 representation of floats map them int. then, maths ints.

note following code not adapted negative numbers, , not take account special floats values (nan, infinities...)

size_t numoffloats(const float min, const float max){     // assert 0 <= min <= max     // assert sizeof(float) == sizeof(int32_t)     const int32_t min_i = *reinterpret_cast<const int32_t*>(&min);     const int32_t max_i = *reinterpret_cast<const int32_t*>(&max);     return max_i-min_i+1; } 

also, can list them when know mapping ints:

void print_successive_floats(const float min, const float max){     const int32_t min_i = *reinterpret_cast<const int32_t*>(&min);     const int32_t max_i = *reinterpret_cast<const int32_t*>(&max);     for(int32_t = min_i; i<=max_i; ++i){         float f = *reinterpret_cast<float*>(&i);         std::cout << f << std::endl;     } } 

for completeness, in order match api:

vector<float> enumallfloats(const float min, const float max){     vector<float> out;     out.reserve(numoffloats(min, max));     const int32_t min_i = *reinterpret_cast<const int32_t*>(&min);     const int32_t max_i = *reinterpret_cast<const int32_t*>(&max);     for(int32_t = min_i; i<=max_i; ++i){         float f = *reinterpret_cast<float*>(&i);         out.push_back(f);     }     return out; } 

beware of huge vectors =)


Comments