Module 29: C++ Math and AlgorithmsAdvanced40 min read
<cmath> Functions & Modern <random> Number Generation
Use <cmath> (pow, sqrt, abs, trig, log) and replace C's rand() with <random> Mersenne Twister (std::mt19937) and uniform/normal distributions.
Key Takeaways & Core Concepts
- (
std::mt19937, seeded viastd::random_device) from Distributions (std::uniform_int_distribution,std::normal_distribution).
1. `<cmath>` & Numerical Functions
Provides std::abs, std::pow, std::sqrt, std::hypot, std::ceil, std::floor, std::round, std::sin/cos/tan, and std::log/exp.
1. mt19937 Engine & Uniform Real Distribution
1#include <iostream>
2#include <random>
3#include <cmath>
4
5int main() {
6 std::mt19937 rng(2026);
7 std::uniform_int_distribution<int> dice(1, 6);
8 std::cout << "Roll: " << dice(rng) << ", hypot(3,4) = " << std::hypot(3.0, 4.0) << "\n";
9 return 0;
10}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
10 lines
Note: Generates unbiased dice rolls and computes Euclidean distance with `std::hypot`.
2. Modern `<random>` vs. Legacy `rand()`
std::rand() has poor statistical distribution and modulo bias. Modern C++ <random> separates Engines (std::mt19937, seeded via std::random_device) from Distributions (std::uniform_int_distribution, std::normal_distribution).
Practice & AssessmentC++ Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)