views:

203

answers:

7

Hello, 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?

+21  A: 

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.

Kendrick
+3  A: 

Can you generate a number from 0-2100 and subtract 100?

n8wrl
+4  A: 

Generate a random number between 0 and 2100, and subtract 100.

Jez
+2  A: 

Here's teh codez.

#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;
    }

}
John Dibling
This will not give an even distribution! Also, finding the minimum and maximum of 100000 such numbers is not relevant to the question.
Cornelius Scarabeus
Also if by chance `val` was `-100` every time, the resulting `max` would be wrong. Ditto for minimum.
Ben Voigt
@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
+1  A: 

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
+1  A: 

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

David
+2  A: 

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<int> dist(-100,2100);

std::cout << dist(rng) << '\n';
Blastfurnace
For those without TR1, boost::random is quite close.
MSalters