Skip to content

Commit fdd64a1

Browse files
committed
another rng (experimental)
1 parent 77b3e7c commit fdd64a1

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
* java-math-library is a Java library focused on number theory, but not necessarily limited to it. It is based on the PSIQS 4.0 factoring project.
3+
* Copyright (C) 2018-2025 Tilman Neumann - tilman.neumann@web.de
4+
*
5+
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License
6+
* as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
7+
*
8+
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
9+
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
10+
*
11+
* You should have received a copy of the GNU General Public License along with this program;
12+
* if not, see <http://www.gnu.org/licenses/>.
13+
*/
14+
package de.tilman_neumann.jml.random;
15+
16+
import org.apache.logging.log4j.Logger;
17+
import org.apache.logging.log4j.LogManager;
18+
19+
import de.tilman_neumann.util.ConfigUtil;
20+
21+
/**
22+
* Java port of Marsaglia's xorshf generator.
23+
* @see https://stackoverflow.com/questions/1640258/need-a-fast-random-generator-for-c<br/><br/>
24+
*
25+
* <strong>WARNING: This class is experimental!</strong> SpRand32 looks faster for numbers close to 31 bit.
26+
* Maybe I need to improve the conversion from C "unsigned long" to Java int (shifts, masks etc.).
27+
*
28+
* @author Tilman Neumann
29+
*/
30+
public class Xorshf32 {
31+
private static final Logger LOG = LogManager.getLogger(Xorshf32.class);
32+
33+
int x=123456789, y=362436069, z=521288629;
34+
35+
public int nextInt(int max) {
36+
int t;
37+
x ^= x << 16;
38+
x ^= x >> 5;
39+
x ^= x << 1;
40+
41+
t = x;
42+
x = y;
43+
y = z;
44+
z = t ^ x ^ y;
45+
46+
return Math.abs(z%max);
47+
}
48+
49+
public static void main(String[] args) {
50+
ConfigUtil.initProject();
51+
Xorshf32 rng = new Xorshf32();
52+
for (int i=0; i<1000; i++) {
53+
LOG.info("rand(" + i + ") = " + rng.nextInt(10));
54+
}
55+
}
56+
}

0 commit comments

Comments
 (0)