The new Random float generator

    This site uses cookies. By continuing to browse this site, you are agreeing to our Cookie Policy.

    • The new Random float generator

      Hi,

      This is my first post here, so I feel like I should start by saying that of all the books I have bought so far on the subject of game development (a nice handful), GC3 has been far and away the best one (and I'm only half way through!).

      Anyway, I ran into some trouble with the random number code tonight and thought I would post my solution in case anyone else goes through the same confusion I did :)


      I was poking around in the CRandom class mentioned in the book and provided in the source code, and decided to try grabbing some floats using the method that's documented as new for the 3rd edition:

      Source Code

      1. // Returns a random float between 0.0f-1.0f
      2. // NEW for Game Code Complete 3rd Edition!
      3. float CRandom::Random()
      4. {
      5. int r = (float)Random(0xffffffff);
      6. float divisor = (float)0xffffffff;
      7. return (r / divisor) + 0.5f;
      8. }

      As I understand it, by catching r as an int and not an unsigned int, values > 2^31 will cause r to become the negative of INT_MAX, which in turn will cause the function to return 0.0000 instead of a value from 0 to .5 (leaving you with either 0 or a float >= .5 and <=1). To fix the issue I made r an unsigned int and got rid of the +0.5 at the end like so:

      Source Code

      1. float CRandom::Random()
      2. {
      3. unsigned int r = (float)Random(0xffffffff);
      4. float divisor = (float)0xffffffff;
      5. return (r / divisor);
      6. }


      Hope this helps someone,

      Soufi
    • RE: The new Random float generator

      Another bug? I've got to talk to my beta readers about this one! Turing, how did we misss this one???

      :) Excellent catch - we'll fix it.
      Mr.Mike
      Author, Programmer, Brewer, Patriot