N
N
Nanami12018-02-03 15:07:52
C++ / C#
Nanami1, 2018-02-03 15:07:52

srand function in range > 100,000?

Is it possible to use the srand function in C++ to select a range of pseudo-random numbers from 1 to 100,000?
Or maybe there is some other function, but with the same requirement: to fill the array with pseudo-random elements in the range from 0 to 100,000?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
GavriKos, 2018-02-03
@GavriKos

The srand function does not generate anything at all. Generates rand. The range is easy to expand:
cppstudio.com/post/834

J
jcmvbkbc, 2018-02-03
@jcmvbkbc

We need to combine the bits of several random values ​​generated by rand, so that we get a number that has as many significant bits as there are in the upper bound of the range. And then leave only the values ​​​​included in the range, discard the rest and generate again. For example:

#include <inttypes.h>
#include <stdlib.h>

static int width(uint64_t v)
{
    int i;

    for (i = 0; v; ++i)
        v >>= 1;
    return i;
}

uint64_t big_rand(uint64_t low, uint64_t high)
{
    uint64_t d = high - low;
    int rn;
    int n;

    assert(low < high);
    rn = width(RAND_MAX);
    n = width(d);
    for (;;) {
        uint64_t v = 0;
        int i;

        for (i = 0; i < n; i += rn) {
            v |= rand() << i;
        }
        if (i != n) {
            v &= ~(((UINT64_C(1) << (i - n)) - 1) << n);
        }
        if (v <= d) {
            return v + low;
        }
    }
}

A
Alexander Taratin, 2018-02-04
@Taraflex

en.cppreference.com/w/cpp/numeric/random/uniform_i...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question