package tiny_libs

  1. Overview
  2. Docs
From-scratch libraries for teaching: graphics, audio, compression, crypto, networking and more

Install

dune-project
 Dependency

Authors

Maintainers

Sources

0.3.6.tar.gz
md5=7c636383d146d30ac6f2fa234a6253c8
sha512=c79f3823c5f8f57e5038eb640d487c61168b84aa07c61999d6622ef9fd0c890e2b03b4c6a7cdbbe9352a49e25dda00ac7bb14693cee8e3d7beeed251351a2af0

doc/src/tiny_libs.random/Lehmer.ml.html

Source file Lehmer.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
(* Claude Code
 *
 * Copyright (C) 2026 Yoann Padioleau
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public License
 * (LGPL) as published by the Free Software Foundation; either version
 * 2 of the License, or (at your option) any later version.
 *)

(* See Lehmer.mli *)

type t = int

let m = 2147483647 (* 2^31 - 1, a prime *)
let a = 16807 (* 7^5 *)
let q = m / a (* 127773 *)
let r = m mod a (* 2836 *)

let of_int (n : int) : t =
  let s = abs (n mod m) in
  if s = 0 then 1 else s

(* MurmurHash3's fmix32, on Int32 (wrapping at 2^32 natively and in a
 * browser alike) *)
let fmix32 (h : int32) : int32 =
  let xorshift k h = Int32.logxor h (Int32.shift_right_logical h k) in
  h |> xorshift 16 |> Int32.mul 0x85ebca6bl |> xorshift 13 |> Int32.mul 0xc2b2ae35l |> xorshift 16

let scramble (n : int) : t =
  (* the low 31 bits of the hash, a non-negative int on both platforms *)
  of_int (Int32.to_int (Int32.logand (fmix32 (Int32.of_int n)) 0x7fffffffl))

let next (s : t) : t =
  let t = (a * (s mod q)) - (r * (s / q)) in
  if t > 0 then t else t + m

let to_unit (s : t) : float = float_of_int (s - 1) /. float_of_int (m - 1)

type state = t ref

let make (seed : int) : state = ref (scramble seed)

let draw (st : state) : float =
  st := next !st;
  to_unit !st

let int (st : state) (n : int) : int = min (n - 1) (int_of_float (draw st *. float_of_int n))
let float (st : state) (x : float) : float = draw st *. x