Pseudo random number generator 
Author Message
 Pseudo random number generator

I tried making a PRNG and here is what I came up with.
(With a small testing main for your convenience ;)

#include <stdio.h>
#include <limits.h>

/*
Get a specified bit and shift it to the specified position
*/
#define GET_BIT(i, what_bit, pos) \
    ((!!((i) & (1 << ((what_bit) - 1)))) << ((pos) - 1))

unsigned int my_random(void)
{
    static unsigned int i1 = 0x9abcdef0,
                        i2 = 0x12345678;
    unsigned int hibit;

    /*roll to the left*/
    hibit = !!(i1 & (1 << (sizeof(unsigned int) * CHAR_BIT - 1)));
    i1 <<= 1;
    i1 |= hibit;
    /* xor two arbitrary bits together */
    i1 ^= GET_BIT(i1, 14, 5);

    /*roll to the left*/
    hibit = !!(i2 & (1 << (sizeof(unsigned int) * CHAR_BIT - 1)));
    i2 <<= 1;
    i2 |= hibit;
    /* xor two arbitrary bits together */
    i2 ^= GET_BIT(i2, 13, 2);

    return i2 ^ i1;

Quote:
}

int main(void)
{
    int i;

    for(i = 0;i < 200;i++)
       printf("%u\n", my_random() % 0x10u);
    putchar('\n');
    for(i = 0;i < 200;i++)
       printf("%u\n", my_random());

    return 0;

Quote:
}

What do you think? I know not everything is optimal and everything,
but is this simple generator any good? Tweaking the different
"magic" numbers and the start numbers have an effect. The same goes
for the operator used in the return statement (Allthough less
important).

--
Thomas Stegen
http://www.*-*-*.com/



Mon, 01 Nov 2004 01:27:51 GMT  
 Pseudo random number generator

<snip>

Quote:
> What do you think? I know not everything is optimal and everything,
> but is this simple generator any good? Tweaking the different
> "magic" numbers and the start numbers have an effect. The same goes
> for the operator used in the return statement (Allthough less
> important).

This is not the right place to get your PRNG analysed, in practice
such an analysis is a lot of work. For an introduction on the subject,
consult Knuth. For analysis of non-cryptograqphic PRNG, check
of Mersienne Twister. There are a number of test packs to check
a PRNG, one is DIEHARD.

--
Tor <torust AT online DOT no>
"To this day, many C programmers believe that 'strong typing' just means
pounding extra {*filter*} the keyboard". PvdL



Tue, 02 Nov 2004 09:02:16 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. Pseudo-random number generators

2. Yet another pseudo-random number generator

3. digits of pi useful as pseudo-random number generator?

4. simple pseudo random generator

5. Help! Pseudo Random Function Generator in C

6. random number generator random() questionable!!!?

7. pseudo-random numbers

8. Pseudo-Random Number Generater

9. More pseudo random numbers?

10. a real random number generator?

11. Random number generator

12. Random number generator

 

 
Powered by phpBB® Forum Software