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?
Asked
Active
Viewed 6.1k times
7 Answers
42
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.

Fred Larson
- 60,987
- 18
- 112
- 174

Kendrick
- 3,747
- 1
- 23
- 41
9
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';

Uglylab
- 103
- 1
- 6

Blastfurnace
- 18,411
- 56
- 55
- 70
-
For those without TR1, boost::random is quite close. – MSalters Oct 01 '10 at 08:28
4
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;
}
}

SimplePi
- 95
- 1
- 4
- 15

John Dibling
- 99,718
- 31
- 186
- 324
-
This will not give an even distribution! Also, finding the minimum and maximum of 100000 such numbers is not relevant to the question. – darklon Sep 30 '10 at 13:49
-
Also if by chance `val` was `-100` every time, the resulting `max` would be wrong. Ditto for minimum. – Ben Voigt Sep 30 '10 at 15:36
-
@Cornelius, @Ben: Who cares? It's just a demo. If I had posted just `(rand()%2101)-100` that would have been better than a compilable, runnable sample? Please. – John Dibling Sep 30 '10 at 16:08
1
In C++0x they will enhance this to provide better support for it with a standard library.

David
- 3,324
- 2
- 27
- 31
0
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);

Oliver
- 43,366
- 8
- 94
- 151