Last active
August 19, 2022 08:50
-
-
Save Andersama/d3223cfd9d6b5d4c180c26416172ed7a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #pragma once | |
| #include <stdint.h> | |
| // This software is a derivative of the below and is distributed without any warranty | |
| // see: https://prng.di.unimi.it/MWC128.c | |
| // license: https://creativecommons.org/publicdomain/zero/1.0/ | |
| // This because uint128_t is not universally supported... | |
| #include <intrin.h> //see: https://github.com/yuikns/intrin for gcc and clang | |
| const uint64_t MWC_A1 = 0xff3a275c007b8ee6; | |
| /* The state must be initialized so that 0 < c < MWC_A1 - 1. */ | |
| struct mwc128_random_t { | |
| uint64_t x; | |
| uint64_t c; | |
| }; | |
| __forceinline mwc128_random_t mwc128_init(mwc128_random_t *rng) { | |
| //cheap rng init, use address of rng if in bad state | |
| rng->c = (rng->c) ? (rng->c % (MWC_A1 - 1)) : ((uint64_t)rng % (MWC_A1 - 1)); | |
| rng->c = (rng->c) ? rng->c : (MWC_A1>>1); | |
| return *rng; | |
| }; | |
| __forceinline uint64_t mwc128_random_r(mwc128_random_t *rng) { | |
| mwc128_random_t tmp; | |
| uint64_t c; | |
| tmp.x = _umul128(MWC_A1, rng->x, &tmp.c); | |
| tmp.x = _addcarry_u64(0, tmp.x, rng->c, &c); | |
| tmp.c += c; | |
| rng->c = tmp.x; | |
| return rng->x = tmp.c; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment