0

I am in need of writing UNIX/LINUX srand48 and drand48 functions in C. I am stuck with setting and using a seed value. I have two functions:

#include <math.h>

long int mfml_win_drandX0;  //actual value used for generation

void srand48(long int seedval) 
{
    mfml_win_drandX0=seedval;  //setting seed into mfml_win_drandX0
}

double drand48(void)
{
    static const double a=0x273673163155, 
                        c=0x13,
                m=281474976710656;
/*EDIT: error was here*/
    mfml_win_drandX0=fmod(a*mfml_win_drandX0+c,m);;  //computing the next value
    return mfml_win_drandX0/m; 
}

But when using:

srand48(2) ;

for (int i=0;i<10;i++)
    std::cout<<drand48()<<std::endl;

I get the same number everytime (mfml_win_drandX0) does not change. How to solve this issue?

Misery
  • 689
  • 2
  • 8
  • 25
  • Here I suggested some techniques to generate random number, I think will help you: [Generate Random numbers without using any external functions](http://stackoverflow.com/questions/15038174/generate-random-numbers-without-using-any-external-functions/15040471#15040471) almost all works in Unix/Linux systems – Grijesh Chauhan Jul 23 '13 at 09:09

2 Answers2

3

You cannot guarantee that mfml_win_drandX0 will be in a range that representable by a long int, even if you choose long long for its type. AFAIK this is Undefined Behavior:

C++11 §5/4:

“If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.”

And I guess you should avoid defining m in this way because when you enter a literal that has an integral type, it is defined as an int. Using

m = 281474976710656LL;

is better, however this does not solve your main problem. Also, take care with

mfml_win_drandX0 = a * mfml_win_drandX0 + c;

Where you do a conversion from const double to long.

Community
  • 1
  • 1
DanielTuzes
  • 2,494
  • 24
  • 40
  • @lulyon: pseudo-random number engines are deterministic (so they don't contain real randomness) but it is hard to predict the next number (i.e: the numbers are random), especially if you don't know the algorithm and the seed value :) – DanielTuzes Jul 23 '13 at 09:22
  • It might be helpful to comment on his answer, then - not on your own one – glglgl Jul 23 '13 at 09:23
  • Unfortunatelly due to my low rep I cannot comment on his/her answer yet. – DanielTuzes Jul 23 '13 at 09:25
0

What do you expect to get though? There is nothing random in your code. a, c, m are all constant, you won't get different result util changing mfml_win_drandX0.

lulyon
  • 6,707
  • 7
  • 32
  • 49
  • 2
    It is a linear random number generator, it works based on this equation. You begin with some value and then copute so called pseudo random values. – Misery Jul 23 '13 at 09:46
  • @Misery Good. That explains everything. – lulyon Jul 23 '13 at 13:10