Sign in to follow this  
zoner7

Produce negative values with a random number generator

Recommended Posts

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

Share this post


Link to post
Share on other sites
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));
}

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
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.0
x = 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]

Share this post


Link to post
Share on other sites
"rand() % (Max+1) - (Max/2) +.01,"

Table of precedence!

it should be

( rand()% (Max + 1) ) - Max/2;




"Also, is there any way that I can make Max a float less than 1 and still have the
program work? "


//return float from min to max
float randF(int min, int max)
{
float num = (float)rand()/RAND_MAX * (max-min) + min;

return num;
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this