Results 1 to 2 of 2

Thread: Generate pseudo-random 16 bit number

  1. #1

    Thread Starter
    Frenzied Member 2kaud's Avatar
    Join Date
    May 2014
    Location
    England
    Posts
    1,169

    Generate pseudo-random 16 bit number

    I want to generate a 16 bit pseudo-random number using only 16 bit variables. This will then be used to generate pseudo-random numbers in the range mn to mx (typically 10 to 700). I've come across this code in c:

    Code:
    short x = 3030;
     
    unsigned xorshift( )
    {
        x ^= x << 7;
        x ^= x >> 9;
        x ^= x << 8;
        return x;
    }
    
    short getrnd(short mn, short mx) {
    	short r = xorshift();
    	short mod = mx - mn + 1;
    	r = r % mod;
    	r = r + mn;
    	return r;
    }
    The language is un-important. I'm more interested in the algorithm used. The algorithm needs to be fairly simple and quick. This seems to be ok but is there a better algorithm than this please?
    All advice is offered in good faith only. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  2. #2

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width