Reputation: 64306
I have to generate numbers in range [-100; +2000] in c++. How can I do this with rand if there is only positive numbers available? Are there any fast ways?
Upvotes: 16
Views: 65053
Reputation: 37
I know this might be too late, but there you go:
Mathematically speaking:
Let a1
and an
be the minimum and maximum values for the pseudo-random integers to be generated - then the possible values for these integers are the same as those between 0
and an - a1
after the addition of a1
to each of these values.
For example,
-100
and 2000
, generate random integers between 0
and 2100
(2000 - (-100) = 2100) and then add -100
to each resulting number.100
and 2000
, generate random integers between 0
and 1900
(2000 - 100 = 1900) and then add 100
to each resulting number.
You can try this formula with small values for a1
and an
to better understand the idea.
Upvotes: 1
Reputation: 18652
You can use the C++ TR1 random functions to generate numbers in the desired distribution.
std::random_device rseed;
std::mt19937 rng(rseed());
std::uniform_int_distribution<int> dist(-100,2100);
std::cout << dist(rng) << '\n';
Upvotes: 10
Reputation: 101456
Here is the code.
#include <cstdlib>
#include <ctime>
int main()
{
srand((unsigned)time(0));
int min = 999, max = -1;
for( size_t i = 0; i < 100000; ++i )
{
int val = (rand()%2101)-100;
if( val < min ) min = val;
if( val > max ) max = val;
}
}
Upvotes: 3
Reputation: 3442
In C++0x they will enhance this to provide better support for it with a standard library.
http://www2.research.att.com/~bs/C++0xFAQ.html#std-random
Upvotes: 1
Reputation: 3787
generate a random number between 0 and 2100 then subtract 100.
A quick google search turned up a decent looking article on using Rand(). It includes code examples for working with a specific range at the end of the article.
Upvotes: 44
Reputation: 45111
Currently my C++ syntax is a little rusty, but you should write a function that takes two parameters: size
and offset
.
So you generate numbers with the given size
as maximum value and afterwards add the (negative) offset to it.
The function would look like:
int GetRandom(int size, int offset = 0);
and would be called in your case with:
int myValue = GetRandom(2100, -100);
Upvotes: 0