Skip to content

PCG

PCG

The PCG library provides a number of better random number generators.

The library has a interface that resembles standard C++ number generators with generators that:

  • Do not fail statistical tests for randomness
  • Ensure unpredictability and safety
  • Are fast and don't require large amounts of memory
  • Provide useful features such as "jump ahead"
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
find_package(pcg-cpp QUIET)
if (NOT pcg-cpp_FOUND)
    FetchContent_Declare(pcg-cpp GIT_REPOSITORY https://github.com/imneme/pcg-cpp.git GIT_TAG v0.98.1)
    FetchContent_GetProperties(pcg-cpp)
    if (NOT pcg-cpp_POPULATED)
        FetchContent_Populate(pcg-cpp)
        # Create header-only library with pcg-cpp include files
        add_library(pcg-cpp INTERFACE)
        target_include_directories(pcg-cpp INTERFACE ${pcg-cpp_SOURCE_DIR}/include)
    endif ()
endif()
add_executable(pcg pcg.cpp)
target_link_libraries(pcg pcg-cpp)

1
pcg32 rng(42u, 54u);

1
rng.seed(pcg_extras::seed_seq_from<std::random_device>());

1
std::cout << "Random number: " << rng() << '\n';

1
std::cout << "Flip coin: " << rng(2) << '\n';

1
std::cout << "Roll dice: " << rng(6) << '\n';

1
2
3
std::cout << "Generator state: " << rng << '\n';
std::cout << "Result size: " << sizeof(pcg32::result_type) * 8 << "bits" << '\n';
std::cout << "Period: 2^" << pcg32::period_pow2() << '\n';

1
2
std::uniform_real_distribution<double> distribution(1.0, 10.0);
std::cout << distribution(rng) << '\n';

Share Snippets