bhylu.com

Advertisements

C++ Math and Random Numbers

Calculate a route distance and demonstrate a bounded draw without depending on a library-specific random sequence.

How it works

cmath declares numerical functions with domain and range contracts. hypot calculates a distance without naively squaring two potentially large intermediates. random supplies engines and distributions with separate responsibilities: an engine generates stateful pseudo-random values and a distribution maps them into a requested domain. A fixed seed helps reproduce an engine sequence, but distribution algorithms need not produce identical results across all standard libraries. These facilities are for simulation, not security tokens.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror math-random.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · math-random.cpp

#include <iostream>
#include <cmath>
#include <random>

int main() {
    std::cout << "Distance: " << std::hypot(3.0, 4.0) << " km\n";
    std::mt19937 engine{19};
    std::uniform_int_distribution<int> station{1, 4};
    int selected = station(engine);
    std::cout << "Draw within range: " << (selected >= 1 && selected <= 4) << '\n';
}

Expected result

Distance: 5 km
Draw within range: 1

The geometric fixture gives a checkable five-kilometre result. The random output reports an invariant rather than one implementation’s mapped number. For arbitrary measurements, validate finite values and document tolerances. Functions such as sqrt and log have input domains; formatting a NaN is not an adequate application error policy.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.