简体   繁体   中英

I have a random Number Generator that uses a XOR shift algorithm, using a global variable. Is there another method to accomplish this?

I built this "Random" number Generator, and it works exactly like its supposed to. But I feel like the use of a Global variable in this way is cursed, and there must be a better way of accomplishing the same thing.

unsigned int State = 1804289383;
unsigned int get_random_U32_number() {
    unsigned int Number = State;
    Number ^= Number << 13;
    Number ^= Number >> 17;
    Number ^= Number << 5;
    State = Number;
    return Number;
}

Not sure what else to try, I can't use any built like function like rand() for this project.

Another approach, slightly different from @dbush's answer:

unsigned int get_random_U32_number( void ) {
    static unsigned int State = 1804289383;

    unsigned int Number = State;
    Number ^= Number << 13;
    Number ^= Number >> 17;
    Number ^= Number << 5;
    State = Number;
    return Number;
}

The change to get_random_U32_number( void ) makes it explicit that the function takes no arguments.

You can change your function to take the address of the current state variable as a parameter.

unsigned int get_random_U32_number(unsigned int *State) {
    unsigned int Number = *State;
    Number ^= Number << 13;
    Number ^= Number >> 17;
    Number ^= Number << 5;
    *State = Number;
    return Number;
}

This allows the function to be reentrant.

Make it static to reduce its scope to the local file.

// unsigned int State = 1804289383;
static unsigned int State = 1804289383;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM