How to avoid global variables and extern.

S

StephQ

I'm facing the following problem: I'm using the Gnu Scientific Library
(it is a C math library), and in particular random number generation
algorithms. Example code is:

....
gsl_rng * r;
....
double u = gsl_rng_uniform (r);

The problem is that r "represent" the iteration of the random number
generator algorithm, so it needs to be accessible every time you need
to generate a new random number. In C you can solve the problem by:

1) passing r to every function that needs to generate random numbers
(a burden....)
2) define r as global variable and use extern in evey file (not very
elegant)

I'm wondering if there is a better way to solve the problem in c++. I
also would like to toggle any explicit dependence in my code to the
gsl. This prompted the creation of a wrapper class like:

class RandomNumberGenerator
{
private:
gsl_rng* r;

public:

RandomNumberGenerator() ;

double generateUniform();

};

Then I would like to have something like a unique object of this class
available everywhere that does not need to be initilized (static?)
Is it possible to accomplish this task?
Do you have some better solutions to propose?
Thank you in advance for any help.

StephQ
 
H

Howard

StephQ said:
I'm facing the following problem: I'm using the Gnu Scientific Library
(it is a C math library), and in particular random number generation
algorithms. Example code is:

...
gsl_rng * r;
...
double u = gsl_rng_uniform (r);

The problem is that r "represent" the iteration of the random number
generator algorithm, so it needs to be accessible every time you need
to generate a new random number. In C you can solve the problem by:

1) passing r to every function that needs to generate random numbers
(a burden....)
2) define r as global variable and use extern in evey file (not very
elegant)

How about defining r as a global variable, then declaring it as extern in
just *one* header file, and simply including that header in any
implementation file which needs to use r?

(Bad name, "r", though. Something more descriptive of its purpose, and less
likely to have a name clash with local variables, would be better.)

-Howard
 
R

Roland Pibinger

How about defining r as a global variable, then declaring it as extern in
just *one* header file, and simply including that header in any
implementation file which needs to use r?

Non-const global variables have severe drawbacks and are usually not
considered good style. Since the variable is needed to '"represent"
the iteration of the random number generator algorithm' I don't think
it's a 'burden' to pass it to functions.
 
G

Gianni Mariani

Roland said:
Non-const global variables have severe drawbacks and are usually not
considered good style. Since the variable is needed to '"represent"
the iteration of the random number generator algorithm' I don't think
it's a 'burden' to pass it to functions.


I second that.

For classes at the "application" level, I usually practice passing
around an "environment" class that contains resources such as a
preferences manager, logging manager and anything else like this.

In the Austria C++ alpha (http://netcabletv.org/public_releases/) there
is an Environment (at_env.h) template which does just that.
 
G

Greg Herlihy

I'm facing the following problem: I'm using the Gnu Scientific Library
(it is a C math library), and in particular random number generation
algorithms. Example code is:

...

gsl_rng * r;
...

double u = gsl_rng_uniform (r);

The problem is that r "represent" the iteration of the random number
generator algorithm, so it needs to be accessible every time you need
to generate a new random number. In C you can solve the problem by:

1) passing r to every function that needs to generate random numbers
(a burden....)
2) define r as global variable and use extern in evey file (not very
elegant)

Why not implement a function that wraps the library routine:

double GenerateRandomNumber()
{
static gsl_rng * r = NULL;

return gsl_rng_uniform( r);
}

Greg
 
J

Jim Langston

StephQ said:
I'm facing the following problem: I'm using the Gnu Scientific Library
(it is a C math library), and in particular random number generation
algorithms. Example code is:

...
gsl_rng * r;
...
double u = gsl_rng_uniform (r);

The problem is that r "represent" the iteration of the random number
generator algorithm, so it needs to be accessible every time you need
to generate a new random number. In C you can solve the problem by:

1) passing r to every function that needs to generate random numbers
(a burden....)
2) define r as global variable and use extern in evey file (not very
elegant)

I'm wondering if there is a better way to solve the problem in c++. I
also would like to toggle any explicit dependence in my code to the
gsl. This prompted the creation of a wrapper class like:

class RandomNumberGenerator
{
private:
gsl_rng* r;

public:

RandomNumberGenerator() ;

double generateUniform();

};

Then I would like to have something like a unique object of this class
available everywhere that does not need to be initilized (static?)
Is it possible to accomplish this task?
Do you have some better solutions to propose?
Thank you in advance for any help.

class RandomNumberGenerator
{
public:
double GenerateUniform() { return gsl_rng_uniform (&Seed) };
private:
static gsl_rng Seed;
};

gsl_rng RandomNumberGenerator::Seed = 0;

Notice, Seed is declared as an instance, not as a pointer. gsl_rng_uniform
needs the address of the variable which is accomplished by passing the
address of seed. In your sample you never allocated storage for r.
 
J

Jim Langston

Greg Herlihy said:
Why not implement a function that wraps the library routine:

double GenerateRandomNumber()
{
static gsl_rng * r = NULL;

return gsl_rng_uniform( r);
}

Yes, this would work better than a class, IMO. Just have a static variable
in a function. Of course it should probably be:

double GenerateRandomNumber()
{
static gsl_rng r = 0;
return gsl_rng_uniform(&r);
}

or whatever you initialize gsl_rng with.
 
A

anon

Jim said:
class RandomNumberGenerator
{
public:
double GenerateUniform() { return gsl_rng_uniform (&Seed) };

Would it be better to make this static as well? Then you wouldn't have
to create objects of this class.
 
S

StephQ

class RandomNumberGenerator
Would it be better to make this static as well? Then you wouldn't have
to create objects of this class.

Do you see any evident problem in the the following solution?

class RandomNumber
{
private:
const gsl_rng_type* T;
gsl_rng* r;

public:

RandomNumber() ;

// Uniform random number generator.
double generateUniform();

// Distributions random number generators.
double generateGaussian(double mu, double sigma);

......

};

static RandomNumber randomNumber;

I would like to avoid passing r around because:
1) it's related to the use of the gsl library. And I would like to be
felixible about the library used for random number generation.
2) in stochastic simulations too many algorithms depend on the
generations of random numbers. I would really have to pass r even to
class constructors and so on.....

p.s. I know it is not a good name, r. It was just an example from the
gsl documentation :)

Thank you
StephQ
 
A

anon

StephQ said:
Do you see any evident problem in the the following solution?

class RandomNumber
{
private:
const gsl_rng_type* T;
gsl_rng* r;

public:

RandomNumber() ;

// Uniform random number generator.
double generateUniform();

// Distributions random number generators.
double generateGaussian(double mu, double sigma);

......

};

static RandomNumber randomNumber;

I would like to avoid passing r around because:
1) it's related to the use of the gsl library. And I would like to be
felixible about the library used for random number generation.
2) in stochastic simulations too many algorithms depend on the
generations of random numbers. I would really have to pass r even to
class constructors and so on.....

So, you want to use the solution from Greg Herlihy:
double GenerateRandomNumber()
{
static gsl_rng * r = NULL;

return gsl_rng_uniform( r);
}

Or you can put this function to a class, and declare it static, you will
not have to pass your r to constructor:
/// in the header file
class RandomNumber
{
public:
static double generate();
}

/// in the cpp file
double RandomNumber::generate()
{
static gsl_rng * r = NULL;
return gsl_rng_uniform( r );
}

You can call it like:
RandomNumber::generate()
from any file including RandomNumber header file
 
S

StephQ

So, you want to use the solution from Greg Herlihy:
double GenerateRandomNumber()
{
static gsl_rng * r = NULL;

return gsl_rng_uniform( r);
}


The problem with this soulution is that r needs to be initilized only
once , by
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
I should not touch it anymore (it is automatically modified when I
call gsl_rng_uniform (r))
Or you can put this function to a class, and declare it static, you will
not have to pass your r to constructor:
/// in the header file
class RandomNumber
{
public:
static double generate();

}

/// in the cpp file
double RandomNumber::generate()
{
static gsl_rng * r = NULL;
return gsl_rng_uniform( r );

}

But I still have to create the class RandomNumber and pass it around?
Or am I missing something?

I'm doing something different. I'm creating a static class that gets
initilized at compile time.
There is no static variable in the class and no static function. It's
the class that is static.
And it's declared in the header.

I use it like:

#include <randomnumber.hpp>
......
double u = randomNumber.generateUniform(); //not RandomNumber. ....

I'm just wondering if this is considered a bad solution for reasons
that I'm missing.
In particular, this code should end up inside a dll library.
Would there be any problem with these? Will I be able to access the
static RandomNumber randomNumber from a C++ source file linked to the
dll library?

To sum up I need to:
1) have r automatically initilized when the program start.
2) have the functions that generate the random numbers accessibles
everywhere in the program
3) do not have to pass anything around

Regards
StephQ
 
S

StephQ

The problem with this soulution is that r needs to be initilized only
once , by
gsl_rng_env_setup();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
I should not touch it anymore (it is automatically modified when I
call gsl_rng_uniform (r))

Thinking again about it I may have said something stupid :)
r , beeing a static variable, gets initilized at runtime and not every
time I call the function right?

I still get the problem that r is also used by other functions (that
generate random numbers from other distributions).

StephQ
 
S

StephQ


I just checked out, and yes it is a solution to my problem.
Now I have two alternatives:

* define a "normal" class and make a static instantation of it
* define a class with static member data and static member functions

The only difference I see is that using the first approach I can
instantiate other objects of the class.
Not sure if it is too useful.....

StephQ
 
A

anon

StephQ said:
I just checked out, and yes it is a solution to my problem.
Now I have two alternatives:

* define a "normal" class and make a static instantation of it

.... and go back to global variables and extern ;)
* define a class with static member data and static member functions

The only difference I see is that using the first approach I can
instantiate other objects of the class.

Try to make classes and objects as small and simple as possible
 
J

Jim Langston

StephQ said:
I just checked out, and yes it is a solution to my problem.
Now I have two alternatives:

* define a "normal" class and make a static instantation of it
* define a class with static member data and static member functions

The only difference I see is that using the first approach I can
instantiate other objects of the class.
Not sure if it is too useful.....

If you have other functions that use r then why not wrap them all in the
class with static methods? As for having to instantize r, the I would do a
check in the functions. Peudo code:

class Randomize
{
public:
static double RandomNumber() { if ( r == NULL ) init(); /* use r here
*/ }
static double SomeOtherMethod() { if ( r == NULL ) init(); /* use r here
*/ }
private:
static sometype* r;
static void Init()
{
if ( r = NULL )
{
gsl_rng_env_setup();
sometype T = gsl_rng_default;
r = gsl_rng_alloc (T);
}
}
};

sometype Randomize::r = NULL;
 
G

Greg Herlihy

If you have other functions that use r then why not wrap them all in the
class with static methods? As for having to instantize r, the I would do a
check in the functions. Peudo code:

class Randomize
{
public:
static double RandomNumber() { if ( r == NULL ) init(); /* use r here
*/ }
static double SomeOtherMethod() { if ( r == NULL ) init(); /* use r here
*/ }
private:
static sometype* r;
static void Init()
{
if ( r = NULL )
{
gsl_rng_env_setup();
sometype T = gsl_rng_default;
r = gsl_rng_alloc (T);
}
}

};

sometype Randomize::r = NULL;

I think a namespace would be better suited than a class - since no
objects of this class are ever actually allocated. As for the issue of
accessing "r" from multiple functions - I would just encapsulate one
level deeper in the calling chaing

For example, I would suggest declaring a header file along these
lines:

// gsl.hpp

namespace gsl
{
double GetGeometricRandomNumber( double p);
double GetPoissonRandomNumber( double mu);
...
}

and then placing the corresponding implementation in a source file:

// gsl.cpp

namespace gsl
{
int * get_r()
{
static int *r = gsl_rng_alloc(gsl_rng_default);

return r;
}

double GetGeometricRandomNumber( double p)
{
return gsl_ran_geometric( get_r(), p);
}

double GetPoissonRandomNumber( double mu)
{
return gsl_ran_poisson( get_r(), mu);
}
}

Greg
 
A

anon

Greg said:
I think a namespace would be better suited than a class - since no
objects of this class are ever actually allocated. As for the issue of
accessing "r" from multiple functions - I would just encapsulate one
level deeper in the calling chaing

For example, I would suggest declaring a header file along these
lines:

// gsl.hpp

namespace gsl
{
double GetGeometricRandomNumber( double p);
double GetPoissonRandomNumber( double mu);
...
}

and then placing the corresponding implementation in a source file:

// gsl.cpp

namespace gsl
{
int * get_r()
{
static int *r = gsl_rng_alloc(gsl_rng_default);

return r;
}

double GetGeometricRandomNumber( double p)
{
return gsl_ran_geometric( get_r(), p);
}

double GetPoissonRandomNumber( double mu)
{
return gsl_ran_poisson( get_r(), mu);
}
}

Yes, namespace is also good to prevent pollution.

But to me, both solutions looks good.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top