# what is correct range of return value from ofRandom, ofRandomf, ofRandomuf? #3762

Closed
opened this Issue Apr 16, 2015 · 4 comments

Projects
None yet
2 participants
Contributor

### 2bbb commented Apr 16, 2015

 does openFrameworks want to ofRandom(min, max) < max or ofRandom(min, max) <= max? ofRandomf() < 1.0f or ofRandomf() <= 1.0f? for example, in implementation of ofRandom, openFrameworks uses rand() / (RAND_MAX + 1.0f). https://github.com/openframeworks/openFrameworks/blob/master/libs/openFrameworks/math/ofMath.cpp#L48 but, i don't understand what why this code is not rand() / static_cast(RAND_MAX). @novogrammer says "RAND_MAX == 0x7fff in Visual Studio". then rand() / (RAND_MAX + 1.0f) < 1.0f is always true. but, in Xcode/clang, RAND_MAX == 0x7fffffff. and this value causes underflow in float, like static_cast(RAND_MAX) == RAND_MAX + 1.0f returns true. and execute size_t c = 0; for(int i = 0; i < RAND_MAX; i++) { if(1.0f == i / (RAND_MAX + 1.0f)) { c++; } } printf("%d", c); then print 63. this means rand() / (RAND_MAX + 1.0f) < 1.0f is NOT always true. sometimes rand() / (RAND_MAX + 1.0f) == 1.0f is true. i think, this is bug of environment-dependent, and correct code is rand() / (RAND_MAX + 1.0). what's correct range of hope?
Member

### bilderbuchi commented Apr 16, 2015

 see previous (old) discussion in #224. I now think <1/

Contributor

### 2bbb commented Apr 17, 2015

 @bilderbuchi thanks for tell me #224, i couldn't find this issue... i think so too. "anyone hope no overlap in multiple range." and sorry, i found notation in newest version of ofMath.h: A random number in the range [0, max) will be returned. https://github.com/openframeworks/openFrameworks/blob/master/libs/openFrameworks/math/ofMath.h#L30 this is information i need... maybe, remaining is just to solve the problem. i will throw PR about this problem, after i do little more test. thanks.

### 2bbb added a commit to 2bbb/openFrameworks that referenced this issue May 17, 2015

change denominator of ofRandomuf from float to double.
change from (RAND_MAX + 1.0f) to (RAND_MAX + 1.0).
because, if RAND_MAX is sufficiently large, then RAND_MAX + 1.0f == RAND_MAX.
in other words, often rand() / (RAND_MAX + 1.0f) returns 1.0f
see #3762

Merged

Member

### bilderbuchi commented Jun 3, 2015

 I think this can be closed now that #3842 is merged.

Contributor

### 2bbb commented Jun 3, 2015

 @bilderbuchi oh... sorry!! i forgot this issue...! thanks!!