Last active
December 19, 2015 05:21
-
-
Save kewang/6ac7df40106aca684191 to your computer and use it in GitHub Desktop.
Math.random() at V8 engine from https://blog.gslin.org/archives/2015/12/18/6202/
This file contains 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
// MWC1616 (multiply with carry, combining two 16-bit parts) | |
#include <stdio.h> | |
#include <inttypes.h> | |
uint32_t state0 = 1; | |
uint32_t state1 = 2; | |
uint32_t mwc1616(); | |
int main(){ | |
int input = 0; | |
printf("input: "); | |
scanf("%d", &input); | |
for(int i = 0; i < input; i++){ | |
printf("number %d: %" PRIu32 "\n", i + 1, mwc1616()); | |
} | |
return 0; | |
} | |
uint32_t mwc1616() { | |
state0 = 18030 * (state0 & 0xffff) + (state0 >> 16); | |
state1 = 30903 * (state1 & 0xffff) + (state1 >> 16); | |
return state0 << 16 + (state1 & 0xffff); | |
} |
This file contains 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
// xorshift128+ (It uses 128 bits of internal state, has a period length of 2128 - 1) | |
#include <stdio.h> | |
#include <inttypes.h> | |
uint64_t state0 = 1; | |
uint64_t state1 = 2; | |
uint64_t xorshift128plus(); | |
int main(){ | |
int input = 0; | |
printf("input: "); | |
scanf("%d", &input); | |
for(int i = 0; i < input; i++){ | |
printf("number %d: %" PRIu64 "\n", i + 1, xorshift128plus()); | |
} | |
return 0; | |
} | |
uint64_t xorshift128plus() { | |
uint64_t s1 = state0; | |
uint64_t s0 = state1; | |
state0 = s0; | |
s1 ^= s1 << 23; | |
s1 ^= s1 >> 17; | |
s1 ^= s0; | |
s1 ^= s0 >> 26; | |
state1 = s1; | |
return state0 + state1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
rand1 result
rand2 result
無論是 100 或 1000 均無碰撞。