(C++) 'random' sequence generator

Post those lines of code you feel like sharing or find what you require for your project here; or simply use them as tutorials.
Post Reply
bitplane
Admin
Posts: 3204
Joined: Mon Mar 28, 2005 3:45 am
Location: England
Contact:

(C++) 'random' sequence generator

Post by bitplane »

output from rand() differs across systems even if you set the same seed, so I made this litle sequence generator to keep everything in sync :)
It may not be random enough for you though

Code: Select all

class CRandSequence
{
public:
    u32 A, B;

    CRandSequence::CRandSequence(u32 seeda, u32 seedb)
    {
        Set(seeda,seedb);
    }
    
    void CRandSequence::Set(u32 seeda, u32 seedb, u32 loops=0)
    {
        A = seeda+((u32)-1)/2;
        B = seedb+((u32)-1)/2;
        for (s32 n=0; n<loops; ++n) getInt();
    }
    
    // returns the next number in the sequence as a u32
    u32 CRandSequence::getInt()
    {
        u32 ret = A + B;
        A=B; B=ret;
        return ret;
    }
    // returns the next number in the sequence as a float 0.0 to 1.0
    f32 CRandSequence::getFloat()
    {
        u32 ret = A + B;
        A=B; B=ret;
        return (f32) ( (f64)ret/(f64)((u32)-1) );
    }
};

Submit bugs/patches to the tracker!
Need help right now? Visit the chat room
Warchief
Posts: 204
Joined: Tue Nov 22, 2005 10:58 am

Re: (C++) 'random' sequence generator

Post by Warchief »

bitplane wrote:output from rand() differs across systems even if you set the same seed
Are you totally sure about this? Im not saying you are wrong, im really asking if you are sure. Could it be just because of rand implementation in different libs?
jam
Posts: 409
Joined: Fri Nov 04, 2005 3:52 am

Post by jam »

I was thinking he meant on different platforms(linux, windows, unix, etc)?
Post Reply