Created
November 13, 2025 02:08
-
-
Save mydreambei-ai/bfb78503fbeb9f1ede6e8e557c8e7a98 to your computer and use it in GitHub Desktop.
xorshift32 matrix demo
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
| import numpy as np | |
| M = None | |
| def xorshift32(x): | |
| x ^= (x << 13) & 0xFFFFFFFF | |
| x ^= x >> 17 | |
| x ^= (x << 5) & 0xFFFFFFFF | |
| return x | |
| def int_to_bitvec(x, n=32): | |
| """ | |
| [低位, ..., 高位] | |
| """ | |
| return np.array([(x >> i) & 1 for i in range(n)], dtype=np.uint8) | |
| def bitvec_to_int(v): | |
| return sum([v[i] << i for i in range(len(v))]) | |
| def get_M(): | |
| """ | |
| k < 0, left shift, top change 0 means Little -> 0 | |
| k > 0, right shift, bottom change 0 High -> 0 | |
| """ | |
| I = np.eye(32, dtype=np.uint32) | |
| M_a = np.diag(I.diagonal()[:19], k=-13) | |
| M_b = np.diag(I.diagonal()[:15], k=17) | |
| M_c = np.diag(I.diagonal()[:27], k=-5) | |
| Ma = (I + M_a) % 2 | |
| Mb = (I + M_b) % 2 | |
| Mc = (I + M_c) % 2 | |
| return np.mod(Mc @ np.mod(Mb @ Ma, 2), 2) | |
| def matrix_demo_xorshift32(x): | |
| global M | |
| if M is None: | |
| M = get_M() | |
| x_vec = int_to_bitvec(x) | |
| x_next_vec = np.mod(M @ x_vec, 2) | |
| return bitvec_to_int(x_next_vec) | |
| if __name__ == "__main__": | |
| for i in range(100, 1000): | |
| print(matrix_demo_xorshift32(i) == xorshift32(i)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment