Was working on a project with mingw on windows :
C:\Users\...>g++ -dumpversion
4.5.0
When I compiled the code under g++ v 4.2.4 I was getting a segmentation fault – after couple hours I pinned it down to the line :
double decimal = ((double) rand()) / (RAND_MAX + 1);
For some reason this was giving negative values (and one thing led to another).
What reason ?
Edit : cpp :
#include <iostream>
#include "Random.h"
#include <math.h>
using namespace std;
double Random::exponential(int T) {
double decimal = ((double) rand()) / (RAND_MAX + 1);
// std::cout << "decimal : " << decimal << std::endl;
return log(1 - decimal)*(-T);
}
//etc
h:
#ifndef RANDOM_H
#define RANDOM_H
#include <cstdlib>
#include <math.h>
class Random {
public:
static double exponential(int T);
static int random_int(int min, int max);
static bool coin(); //50% true 50% false
};
#endif /* RANDOM_H */
just noticed the double include (of math.h) but this shouldn’t be an issue
In your case,
RAND_MAXis the maximum value for the integer type it is stored in, soRAND_MAX + 1gives you the maximum negative value. Technically this is signed integer overflow which is undefined behaviour so anything can happen.You need to do, as J-16 pointed out,