Old 01-12-2015, 01:05 PM   #1
Solomon
Human being with feelings
 
Solomon's Avatar
 
Join Date: Jan 2011
Location: Seattle, WA
Posts: 43
Default What is rand() actually supposed to do?

The documentation says:

rand(x) -- returns a psuedorandom number between 0 and the parameter

It isn't at all clear to me whether x is expected to be an integer or a real number, and whether the return value should be expected to be in integer or a real number. Also, is "between 0 and the parameter" the closed interval [0,x] or the half-open interval [0,x)?

A little bit of testing reveals that if x >= 2, rand(x) returns a real number between 0 and x. If x < 2, though, rand(x) is between 0 and 1. I don't understand the usefulness of this behavior, but could the documentation at least be amended so as to document it fully?

--Solomon

Last edited by Solomon; 01-12-2015 at 05:23 PM.
Solomon is offline   Reply With Quote
Old 01-12-2015, 04:06 PM   #2
Tale
Human being with feelings
 
Tale's Avatar
 
Join Date: Jul 2008
Location: The Netherlands
Posts: 2,940
Default

I always assumed that it would return [0, x). However, I have just run this simple test, and it seems to suggest that it actually returns (0, x), so with both ends excluded.

Other than that it would seem that rand(x) == rand(floor(max(1, x)), so you can't do rand(0), rand(-1) etc. Although its input is an integer, its return value a float. And yeah, I guess it would be nice if this could be documented more clearly somehow.

Code:
desc:rand test
slider1:1<0,10,.1>x
@slider
x=slider1;a=x+1;z=-1;
@sample
loop(100,y=rand(x);y<a?a=y;y>z?z=y;lt=y<x;nz=y>0);
Tale is offline   Reply With Quote
Old 01-13-2015, 08:44 AM   #3
kuus0
Human being with feelings
 
Join Date: Feb 2011
Posts: 159
Default

Here's the code from WDL nseel-cfunc.c:

Code:
EEL_F NSEEL_CGEN_CALL nseel_int_rand(EEL_F f)
{
  EEL_F x=floor(f);
  if (x < 1.0) x=1.0;

#ifdef NSEEL_EEL1_COMPAT_MODE
  return (EEL_F)(genrand_int32()%(int)x);
#else
  return (EEL_F) (genrand_int32()*(1.0/(double)0xFFFFFFFF)*x);
#endif
}
kuus0 is offline   Reply With Quote
Old 01-13-2015, 05:05 PM   #4
Tale
Human being with feelings
 
Tale's Avatar
 
Join Date: Jul 2008
Location: The Netherlands
Posts: 2,940
Default

So it would seem that rand(x) returns [0, x] after all, although I guess the chance of actually getting exactly 0 or x is very small (~1.0/0xFFFFFFFF), and maybe rounding may also prevent the outcome from being exactly x.
Tale is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -7. The time now is 11:39 PM.


Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2019, vBulletin Solutions Inc.