Produce negative values with a random number generator

Started by
9 comments, last by tnutty 14 years, 9 months ago
Is there a random number generator function that will produce negative as well as positive values. Rand() apparently does not. Clearly I can do a work around for this, but I'm curious if a function exist to perform this operation. I am sure there is something
Advertisement
Yes, there are. If you mention which programming language you are using, we might be able to direct you to some.
I'm using c++
A random number between -10 and 10:

#include <iostream>#include <ctime>#include <boost/random.hpp>int main(){    boost::mt19937 engine(time(0));    boost::uniform_int<int> dist(-10, 10);    std::cout << dist(engine);}


25 random numbers between -10 and 10:

#include <algorithm>#include <iostream>#include <ctime>#include <boost/bind.hpp>#include <boost/random.hpp>int main(){    boost::mt19937 engine(time(0));    boost::uniform_int<int> dist(-10, 10);    std::generate_n(std::ostream_iterator<int>(std::cout, "\n"), 25, boost::bind(dist, engine));}
True rand does not produce negative values but you can adjust it to .


int max = 10;

rand() % max/2 - max/2;

produces values from -5 to 5
Our whole life is a opengl application.
Quote:Original post by tnutty
int max = 10;

rand() % max/2 - max/2;

produces values from -5 to 5

More like rand() % (max+1) - (max/2).
Oh yea, your right.
Our whole life is a opengl application.
I tried this rand() % (Max+1) - (Max/2) +.01, but it doesn't seem to produce any negative values.

Also, is there any way that I can make Max a float less than 1 and still have the program work?
0 to -x: -(rand() % (x + 1))

-x to x: (rand() % (-x - x - 1)) - x

-x to y: (rand() % (-y - x - 1)) - x

-x to -y: -((rand() % (y - x + 1)) + x)



Hopefully that'll help.
Quote:Original post by zoner7
Also, is there any way that I can make Max a float less than 1 and still have the program work?

Oh, you want real numbers. Just use a different distribution.

#include <algorithm>#include <iostream>#include <ctime>#include <boost/bind.hpp>#include <boost/random.hpp>int main(){    boost::mt19937 engine(time(0));    boost::uniform_real<double> dist(-1.0, 1.0);    std::generate_n(std::ostream_iterator<double>(std::cout, "\n"),                    25, boost::bind(dist, engine));}

And if you insist on using the deprecated rand() function:
double x = double(rand()) / RAND_MAX; // random number between  0.0 and  1.0x = 2.0*x - 1.0;                      // random number between -1.0 and +1.0

Oh and if you want numbers between -1.0 inclusive and +1.0 exclusive, use
double x = rand() / (RAND_MAX + 1.0);x = 2.0*x - 1.0;


[Edited by - DevFred on July 24, 2009 7:51:09 PM]

This topic is closed to new replies.

Advertisement