Hey,
I have noticed when you use srand or rand you write:

rand() % 99 + 1

I was wondering about the 1, is it just tradition to use it or is it from 1-99?
Just because i was wondering how i could make it between say 20 and 40 etc

Dani AI

Generated

: the small constant you saw is just an offset to move a zero-based result into a desired interval. correctly drew attention to seeding, and is right to worry about modulo bias — it matters only in some situations and there are simple, robust alternatives.

Use the C++ <random> facilities for a clean, correct answer. Create an engine once, then draw from a uniform distribution for any closed interval. Example:

#include <random>

int randBetween(int low, int high)
{
static std::mt19937 gen(std::random_device{}());
std::uniform_int_distribution<int> dist(low, high);
return dist(gen);
}

Modulo-based mapping of a raw PRNG output is unbiased only when (RAND_MAX+1) divides the desired range exactly. Otherwise some outcomes occur one extra time; the maximum per-value probability error is at most 1/(RAND_MAX+1), so with typical RAND_MAX (often 32767) the bias is tiny for many uses but can be meaningful for statistical work. If you must use the C rand() API, use rejection sampling (draw until the sample falls within a truncated range that is an exact multiple of your target size) to eliminate that bias. Also seed once at program startup instead of reseeding before every call.

For details and the recommended C++ interfaces, see the C++ random overview and the legacy rand/srand documentation:
C++ random overview
rand and srand

Recommended Answers

All 3 Replies

A solution to what you desire is given pretty much straight away, but it makes an interesting read --

It's not, however, a question about srand. That merely 'seeds' rand. You want to get random numbers which is rand.

Ok thank you, sorry for the mistake :S

I skimmed the article, but is the only problem with rand() that RAND_MAX may not be one less than a multiple of your maximum? Like if you do rand()%3, and RAND_MAX+1 is a multiple of 3, will that be truly random?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.