Tuesday Coding Tip 18 — Generating random numbers in C++

3 8 42
calendar_todayschedule1 min read
— Originally published at medium.com

Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.


Classic C way of generating random numbers is to set the current time as a seed and then modulo results of the rand function to get somewhat random numbers (modulo can introduce bias based on the implementation of rand).

#include <iostream>
#include <random>

// Get random integer in range <min, max)
int getRandomNumber(int min, int max)
{
    return rand() % (max - min) + min;
}

int main()
{
    // seeding with current time to get different output each time
    srand(time(NULL));

    for (int i = 0; i < 10; i++)
        std::cout << getRandomNumber(10, 20) << std::endl;
}

C++11 introduces the concept of engines, adaptors, and distributions. Engines are seedable and give you random numbers similar to rand() calls. However, each engine is implemented differently, impacting its speed and memory footprint. Adapters tamper with RNG output, such as shuffling the order of output values or discarding them.

Distributions transform the output from the generators to get values in certain ranges and probabilistic properties, such as the middle value being the most probable (normal distribution). Distributions are more nuanced than just using the modulo operator so their outputs are more suitable for cryptography use-cases.

#include <iostream>
#include <random>

// Get random integer in range <min, max)
int getRandomNumber(int min, int max)
{
    return rand() % (max - min) + min;
}

int main()
{
    std::random_device rd; // non-seedable source of non-deterministic numbers from hardware
    std::mt19937 generator(rd()); // deterministic generator with uniform distribution
                                  // seeded with totally random number

    std::uniform_int_distribution<> distribution(10, 19);

    for (int i = 0; i < 10; i++)
        std::cout << distribution(generator) << std::endl;
}
Part 6 of 7 in Tuesday Coding Tips

1 Comment

1 vote
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Tuesday Coding Tip 17 — Wrapping C APIs

Jakub Neruda - Jun 30

Tuesday Coding Tip 05 - Object initialization in C++

Jakub Neruda - Mar 31

Tuesday Coding Tip 08 — Explicit template specialization

Jakub Neruda - Apr 21
chevron_left
1.2k Points53 Badges
Brno, Czech Republiclinkedin.com/in/jakub-neruda
24Posts
15Comments
12Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Related Jobs

View all jobs →

Commenters (This Week)

6 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!