www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1994/09/26/12:19:53

Date: Mon, 26 Sep 94 09:09:57 EDT
To: roalz AT varano DOT ing DOT unico DOT it
From: richard DOT young AT clark DOT dgim DOT doc DOT ca (Richard Young)
Subject: Correction to (Re: Problem with rand() (fwd))
Cc: djgpp AT sun DOT soe DOT clarkson DOT edu

On my response to you I wrote:

>For your application, they recommend the following:
>
>        roll += int(rand()*_sides) + 1;
>
>This implementation is also attractive because it does not involve a divide 
(the >%) and therefore should be somewhat faster.

which is in error.  I was adapting the fortran version of which ran() 
returns a float between 0 and 1.  The C rand() returns an int between 0 and 
RAND_MAX.  The above code assumes that rand returns a float between 0 and 1. 
 You may change the above for C to 

roll += int(float(rand())/(RAND-MAX+1) * _sides) + 1;

This still should not involve a divide since the /(RAND_MAX+1) is a constant 
and would be implemented as a multiply by 1/(RAND_MAX+1).

Sorry for the error.

Richard Young,
Signal Processing Engineer,
Communications Research Centre,
Ottawa, Canada.



- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019