pax_global_header00006660000000000000000000000064146015313510014511gustar00rootroot0000000000000052 comment=4b4872582aa2335d3daefbc98d02cc18032efb1f stdlib-random-1.2.0/000077500000000000000000000000001460153135100142505ustar00rootroot00000000000000stdlib-random-1.2.0/.gitignore000066400000000000000000000000101460153135100162270ustar00rootroot00000000000000_build stdlib-random-1.2.0/Changelog.md000066400000000000000000000023161460153135100164630ustar00rootroot00000000000000Release 1.2.0 ------------- - `stdlib-random.v5` and `stdlib-random.v5o`: import `Random.int_in_range` functions and friends from OCaml 5.2. - `stdlib-random.v3` and `stdlib-random.v4` library: implement `Random.int_in_range` functions and friends. Release 1.1.0 ------------- - `stdlib-random.v5` and `stdlib-random.v5o`: import `Random.state` serialization functions: `of_binary_string` and `to_binary_string` from OCaml 5.1. - `stdlib-random.v3` and `stdlib-random.v4` library: implement `Random.state` serialization functions: `of_binary_string` and `to_binary_string`. Release 1.0.0 ------------- - `stdlib-random.v5` library: compiler-independent implementation of the Random module of OCaml 5 - `stdlib-random.v5o` library: compiler-independent implementation of the Random module of OCaml 5, in pure OCaml - `stdlib-random.v4` library: compiler-independent implementation of the Random module of OCaml 4 - `stdlib-random.v3` library: compiler-independent implementation of the Random module used from OCaml 3.07 to OCaml 3.11. Initialisation -------------- - Import Random4 module from OCaml 4.** compiler - Import Random5 module from OCaml 5.** compiler stdlib-random-1.2.0/LICENSE000066400000000000000000000650531460153135100152660ustar00rootroot00000000000000In the following, "the OCaml Core System" refers to all files marked "Copyright INRIA" in this distribution. The OCaml Core System is distributed under the terms of the GNU Lesser General Public License (LGPL) version 2.1 (included below). As a special exception to the GNU Lesser General Public License, you may link, statically or dynamically, a "work that uses the OCaml Core System" with a publicly distributed version of the OCaml Core System to produce an executable file containing portions of the OCaml Core System, and distribute that executable file under terms of your choice, without any of the additional requirements listed in clause 6 of the GNU Lesser General Public License. By "a publicly distributed version of the OCaml Core System", we mean either the unmodified OCaml Core System as distributed by INRIA, or a modified version of the OCaml Core System that is distributed under the conditions defined in clause 2 of the GNU Lesser General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU Lesser General Public License. ---------------------------------------------------------------------- GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. one line to give the library's name and an idea of what it does. Copyright (C) year name of author This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. signature of Ty Coon, 1 April 1990 Ty Coon, President of Vice That's all there is to it! -------------------------------------------------- stdlib-random-1.2.0/README.md000066400000000000000000000035041460153135100155310ustar00rootroot00000000000000# Compatibility library for Random number generation This library provides access to the various implementation of the Random module from the OCaml standard library independently of the compiler version. ## Signature compatibility Whenever possible, the signature of the the older Random module has been extended with functions that were added in newer versions. Currently, this means that all `Random*` modules before `v5` shares the exact same type whereas the Random5 module is the only to define a `split` function since previous PRNGs are not splittable. ## stdlib-random.v5 library The `stdlib-random.v5` library uses the same LXM pseudo-random number generator as the one used in OCaml 5. For versions of OCaml that support multiple domains, the global PRNG of this library is a domain local state rather than a global state to avoid any potential contention issue on this global PRNG. Moreover, whenever a new domain is spawn, its global PRNG is split from the PRNG of the parent domain which ensures that both PRNGs are essentially independent. ## stdlib-random.v5o library The `stdlib-random.v5o` library provides a pure OCaml alternative to the `stdlib-random.v5` library which uses a C implementation when updating the PRNG state. ## stdlib-random.v4 library The `stdlib-random.v4` library exposes the lagged-Fibonacci F(55, 24, +) PRNG with a modified addition function used from OCaml 3.12 to OCaml 4.14 . ## stdlib-random.v3 library The `stdlib-random.v3` library exposes the lagged-Fibonacci F(55, 24, +) PRNG used from OCaml 3.07 to OCaml 3.11. Note that this library prioritizes compatibility over correctness. In particular, the state of this generator is not marshallable across architecture with different word size. It is thus advisable to use this PRNG only when compatibility with OCaml 3 PRNG is a strict requirement. stdlib-random-1.2.0/dune000066400000000000000000000000501460153135100151210ustar00rootroot00000000000000(documentation (package stdlib-random)) stdlib-random-1.2.0/dune-project000066400000000000000000000017441460153135100166000ustar00rootroot00000000000000(lang dune 2.7) (name stdlib-random) (version 1.2.0) (generate_opam_files true) (strict_package_deps true) (license "LGPL-2.1-or-later WITH OCaml-LGPL-linking-exception") (maintainers "Florian Angeletti, ") (authors "Damien Doligez" "Xavier Leroy") (source (github ocaml/stdlib-random)) (package (name stdlib-random) (depends (cppo (>= 1.1.0)) (ocaml (>= 4.08.0))) (synopsis "Versioned Random module from the OCaml standard library") (description "The stdlib-random package provides a stable and compiler-independent implementation of all the PRNGs used in the Random module. Those PRNGs are available in the various libraries: - stdlib-random.v3: OCaml 3.07 to 3.11 PRNG - stdlib-random.v4: OCaml 3.12 to 4.14 PRNG - stdlib-random.v5: current OCaml 5.0 PRNG - stdlib-random.v5o: pure OCaml version of the OCaml 5 PRNG All those libraries can be used together and the signature of their Random$n module has been extended to the latest signature whenever possible. ") ) stdlib-random-1.2.0/dune-workspace.dev000066400000000000000000000004271460153135100177020ustar00rootroot00000000000000(lang dune 3.0) (context (opam (switch 4.08.1))) (context (opam (switch 4.09.1))) (context (opam (switch 4.10.2))) (context (opam (switch 4.11.2))) (context (opam (switch 4.12.1))) (context (opam (switch 4.13.1))) (context (opam (switch 4.14.1))) (context (opam (switch 5.0.0))) stdlib-random-1.2.0/index.mld000066400000000000000000000037541460153135100160660ustar00rootroot00000000000000This library provides access to the various implementation of the Random module from the OCaml standard library independently of the compiler version. {1:stdlib-random-consistency Signature compatibility} Whenever possible, the signature of the the older Random module has been extended with functions that were added in newer versions. Currently, this means that all [Random*] modules before [v5] shares the exact same type whereas the Random5 module is the only to define a [split] function since previous PRNGs are not splittable. {1:stdlib-random-v5 The [stdlib-random.v5] library } The {{!module:Random5} stdlib-random.v5 } library uses the same LXM pseudo-random number generator as the one used in OCaml 5. For versions of OCaml that support multiple domains, the global PRNG of this library is a domain local state rather than a global state to avoid any potential contention issue on this global PRNG. Moreover, whenever a new domain is spawn, its global PRNG is split from the PRNG of the parent domain which ensures that both PRNGs are essentially independent. {1:stdlib-random-v5o The [stdlib-random.v5o] library } The {{!module:Random5o}stdlib-random.v5o} library provides a pure OCaml alternative to the {{!module:Random5}stdlib-random.v5} library which uses a C implementation when updating the PRNG state. {1:stdlib-random-v4 The [stdlib-random.v4] library } The {{!module:Random4}stdlib-random.v4} library exposes the lagged-Fibonacci F(55, 24, +) PRNG with a modified addition function used from OCaml 3.12 to OCaml 4.14 . {1:stdlib-random-v3 The [stdlib-random.v3] library } The {{!module:Random3}stdlib-random.v3} library exposes the lagged-Fibonacci F(55, 24, +) PRNG used from OCaml 3.07 to OCaml 3.11. Note that this library prioritizes compatibility over correctness. In particular, the state of this generator is not marshallable across architecture with different word size. It is thus advisable to use this PRNG only when compatibility with OCaml 3 PRNG is a strict requirement. stdlib-random-1.2.0/random3/000077500000000000000000000000001460153135100156135ustar00rootroot00000000000000stdlib-random-1.2.0/random3/dune000066400000000000000000000002301460153135100164640ustar00rootroot00000000000000(library (public_name stdlib-random.v3) (name random3) (preprocess (action (run %{bin:cppo} -V OCAML:%{ocaml_version} %{input-file}))) ) stdlib-random-1.2.0/random3/random3.ml000066400000000000000000000453771460153135100175300ustar00rootroot00000000000000(***********************************************************************) (* *) (* Objective Caml *) (* *) (* Damien Doligez, projet Para, INRIA Rocquencourt *) (* *) (* Copyright 1996 Institut National de Recherche en Informatique et *) (* en Automatique. All rights reserved. This file is distributed *) (* under the terms of the GNU Library General Public License, with *) (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) (* "Linear feedback shift register" pseudo-random number generator. *) (* References: Robert Sedgewick, "Algorithms", Addison-Wesley *) (* The PRNG is a linear feedback shift register. It is seeded by a MD5-based PRNG. *) external random_seed: unit -> int array = "caml_sys_random_seed" module State = struct type t = { st : int array; mutable idx : int } let new_state () = { st = Array.make 55 0; idx = 0 } let assign st1 st2 = Array.blit st2.st 0 st1.st 0 55; st1.idx <- st2.idx let serialization_prefix = "lfsr1:" (* "lfsr" denotes the algorithm currently in use, and '1' is a version number. Each Random algorithm or serialization format should have distinct prefix , so that users get a clean error instead of believing that they faithfully reproduce their previous state and in fact get a differrent stream. Note that there is no constraint to keep the same ":" format or message size in future versions, we could change the format completely if we wanted as long as there is no confusion possible with the previous formats. *) let serialization_prefix_len = String.length serialization_prefix (* Compatibility functions Imported from standard library *) #if OCAML_VERSION < (4,13,0) let get_int32_le s off = let res = ref Int32.zero in for i = 3 downto 0 do let v = Int32.of_int (Char.code s.[off+i]) in res := Int32.(add v (shift_left !res 8)) done; !res let get_int8 s off = Char.code s.[off] let starts_with ~prefix s = let open String in let len_s = length s and len_pre = length prefix in let rec aux i = if i = len_pre then true else if unsafe_get s i <> unsafe_get prefix i then false else aux (i + 1) in len_s >= len_pre && aux 0 #else let get_int32_le = String.get_int32_le let get_int8 = String.get_int8 let starts_with = String.starts_with #endif let to_binary_string s = let prefix = serialization_prefix in let preflen = serialization_prefix_len in let buf = Bytes.create (preflen + 55 * 4 + 1) in Bytes.blit_string prefix 0 buf 0 preflen; for i = 0 to 54 do Bytes.set_int32_le buf (preflen + i * 4) (Int32.of_int (s.st.(i) land 0x3FFFFFFF)) done; Bytes.set_int8 buf (preflen + 55 * 4) s.idx; Bytes.unsafe_to_string buf let of_binary_string buf = let prefix = serialization_prefix in let preflen = serialization_prefix_len in if String.length buf <> preflen + 1 + 55 * 4 || not (starts_with ~prefix buf) then failwith ("Random3.State.of_binary_string: expected a format \ compatible with Random3 PRNG"); let st = new_state () in for i=0 to 54 do let n = get_int32_le buf (preflen + i * 4) in st.st.(i) <- Int32.(to_int @@ logand n 0x3FFFFFFFl) done; st.idx <- get_int8 buf (preflen + 55 * 4); st let full_init s seed = let combine accu x = Digest.string (accu ^ Int.to_string x) in let extract d = (Char.code d.[0] + (Char.code d.[1] lsl 8) + (Char.code d.[2] lsl 16)) lxor (Char.code d.[3] lsl 22) in let seed = if Array.length seed = 0 then [| 0 |] else seed in let l = Array.length seed in for i = 0 to 54 do s.st.(i) <- i; done; let accu = ref "x" in for i = 0 to 54 + max 55 l do let j = i mod 55 in let k = i mod l in accu := combine !accu seed.(k); s.st.(j) <- s.st.(j) lxor extract !accu; done; s.idx <- 0 let make seed = let result = new_state () in full_init result seed; result let make_self_init () = make (random_seed ()) let copy s = let result = new_state () in assign result s; result let min_int31 = -0x4000_0000 (* = -2{^30}, which is [min_int] for 31-bit integers *) let max_int31 = 0x3FFF_FFFF (* = 2{^30}-1, which is [max_int] for 31-bit integers *) (* avoid integer literals for these, 32-bit OCaml would reject them: *) let min_int32 = -(1 lsl 31) (* = -0x8000_0000 on platforms where [Sys.int_size >= 32] *) let max_int32 = (1 lsl 31) - 1 (* = 0x7FFF_FFFF on platforms where [Sys.int_size >= 32] *) (* Return 30 random bits as an integer 0 <= x < 2^30 *) let bits s = s.idx <- (s.idx + 1) mod 55; let newval = (s.st.((s.idx + 24) mod 55) + s.st.(s.idx)) land 0x3FFFFFFF in s.st.(s.idx) <- newval; newval let bits32 s = let b1 = Int32.(shift_right_logical (of_int (bits s)) 14) in (* 16 bits *) let b2 = Int32.(shift_right_logical (of_int (bits s)) 14) in (* 16 bits *) Int32.(logor b1 (shift_left b2 16)) let bits64 s = let b1 = Int64.(shift_right_logical (of_int (bits s)) 9) in (* 21 bits *) let b2 = Int64.(shift_right_logical (of_int (bits s)) 9) in (* 21 bits *) let b3 = Int64.(shift_right_logical (of_int (bits s)) 8) in (* 22 bits *) Int64.(logor b1 (logor (shift_left b2 21) (shift_left b3 42))) (* Return 32 or 64 random bits as a [nativeint] *) let nativebits = if Nativeint.size = 32 then fun s -> Nativeint.of_int32 (bits32 s) else fun s -> Int64.to_nativeint (bits64 s) let rec int31aux s n = let r = bits s in let v = r mod n in if r - v > max_int31 - n + 1 then int31aux s n else v let int s bound = if bound > max_int31 || bound <= 0 then invalid_arg "Random.int" else int31aux s bound let rec int63aux s n = let b1 = bits s in let b2 = bits s in let (r, max_int) = if n <= max_int32 then (* 31 random bits on both 64-bit OCaml and JavaScript. Use upper 15 bits of b1 and 16 bits of b2. *) let bpos = (((b2 land 0x3FFFC000) lsl 1) lor (b1 lsr 15)) in (bpos, max_int32) else let b3 = bits s in (* 62 random bits on 64-bit OCaml; unreachable on JavaScript. Use upper 20 bits of b1 and 21 bits of b2 and b3. *) let bpos = ((((b3 land 0x3FFFFE00) lsl 12) lor (b2 lsr 9)) lsl 20) lor (b1 lsr 10) in (bpos, max_int) in let v = r mod n in if r - v > max_int - n + 1 then int63aux s n else v let full_int s bound = if bound <= 0 then invalid_arg "Random.full_int" else if bound > 0x3FFFFFFF then int63aux s bound else int31aux s bound (* Return an integer between 0 (included) and [n] (excluded). [bound] may be any positive [int]. [mask] must be of the form [2{^i}-1] and greater or equal to [n]. Larger values of [mask] make the function run faster (fewer samples are rejected). Smaller values of [mask] are usable on a wider range of OCaml implementations. *) let rec int_aux s n mask = (* We start by drawing a non-negative integer in the [ [0, mask] ] range *) let r = Int64.to_int (bits64 s) land mask in let v = r mod n in (* For uniform distribution of the result between 0 included and [n] * excluded, the random number [r] must have been drawn uniformly in * an interval whose length is a multiple of [n]. To achieve this, * we use rejection sampling on the greatest interval [ [0, k*n-1] ] * that fits in [ [0, mask] ]. That is, we reject the * sample if it falls outside of this interval, and draw again. * This is what the test below does, while carefully avoiding * overflows and sparing a division [mask / n]. *) if r - v > mask - n + 1 then int_aux s n mask else v (* Return an integer between [min] (included) and [max] (included). The [nbits] parameter is the size in bits of the signed integers we draw from [s]. We must have [-2{^nbits - 1} <= min <= max < 2{^nbits - 1}]. Moreover, for the iteration to converge quickly, the interval [[min, max]] should have width at least [2{^nbits - 1}]. As the width approaches this lower limit, the average number of draws approaches 2, with a quite high standard deviation (2 + epsilon). *) let rec int_in_large_range s ~min ~max ~nbits = let drop = Sys.int_size - nbits in (* The bitshifts replicate the [nbits]-th bit (sign bit) to higher bits: *) let r = ((Int64.to_int (bits64 s)) lsl drop) asr drop in if r < min || r > max then int_in_large_range s ~min ~max ~nbits else r (* Return an integer between [min] (included) and [max] (included). [mask] is as described for [int_aux]. [nbits] is as described for [int_in_large_range]. *) let int_in_range_aux s ~min ~max ~mask ~nbits = let span = max - min + 1 in if span <= mask (* [span] is small enough *) && span > 0 (* no overflow occurred when computing [span] *) then (* Just draw a number in [[0, span)] and shift it by [min]. *) min + int_aux s span mask else (* Span too large, use the alternative drawing method. *) int_in_large_range s ~min ~max ~nbits (* 31bits version to account for the 31 bit PRNG *) let rec int31_in_large_range s ~min ~max = let r = Int32.to_int (bits32 s) in if r < min || r > max then int31_in_large_range s ~min ~max else r let int31_in_range_aux s ~min ~max = let mask = max_int31 in let span = max - min + 1 in if span <= mask (* [span] is small enough *) && span > 0 (* no overflow occurred when computing [span] *) then (* Just draw a number in [[0, span)] and shift it by [min]. *) min + int31aux s span else (* Span too large, use the alternative drawing method. *) int31_in_large_range s ~min ~max (* Return an integer between [min] (included) and [max] (included). We must have [min <= max]. *) let int_in_range s ~min ~max = if min > max then invalid_arg "Random.int_in_range"; (* When both bounds fit in 31-bit signed integers, we use parameters [mask] and [nbits] appropriate for 31-bit integers, so as to yield the same output on all platforms supported by OCaml. When both bounds fit in 32-bit signed integers, we use parameters [mask] and [nbits] appropriate for 32-bit integers, so as to yield the same output on JavaScript and on 64-bit OCaml. *) if min >= min_int31 && max <= max_int31 then int31_in_range_aux s ~min ~max else if min >= min_int32 && max <= max_int32 then int_in_range_aux s ~min ~max ~mask:max_int32 ~nbits:32 else int_in_range_aux s ~min ~max ~mask:max_int ~nbits:Sys.int_size let rec int32aux s n = let b1 = Int32.of_int (bits s) in let b2 = Int32.shift_left (Int32.of_int (bits s land 1)) 30 in let r = Int32.logor b1 b2 in let v = Int32.rem r n in if Int32.sub r v > Int32.add (Int32.sub Int32.max_int n) 1l then int32aux s n else v let int32 s bound = if bound <= 0l then invalid_arg "Random.int32" else int32aux s bound (* Return an [int32] between [min] (included) and [max] (included). We must have [min <= max]. *) let rec int32_in_range_aux s ~min ~max = let r = bits32 s in if r < min || r > max then int32_in_range_aux s ~min ~max else r let int32_in_range s ~min ~max = if min > max then invalid_arg "Random.int32_in_range" else let span = Int32.succ (Int32.sub max min) in (* Explanation of this test: see comment in [int_in_range_aux]. *) if span <= Int32.zero then int32_in_range_aux s ~min ~max else Int32.add min (int32aux s span) let rec int64aux s n = let b1 = Int64.of_int (bits s) in let b2 = Int64.shift_left (Int64.of_int (bits s)) 30 in let b3 = Int64.shift_left (Int64.of_int (bits s land 7)) 60 in let r = Int64.logor b1 (Int64.logor b2 b3) in let v = Int64.rem r n in if Int64.sub r v > Int64.add (Int64.sub Int64.max_int n) 1L then int64aux s n else v let int64 s bound = if bound <= 0L then invalid_arg "Random.int64" else int64aux s bound (* Return an [int64] between [min] (included) and [max] (included). We must have [min <= max]. *) let rec int64_in_range_aux s ~min ~max = let r = bits64 s in if r < min || r > max then int64_in_range_aux s ~min ~max else r let int64_in_range s ~min ~max = if min > max then invalid_arg "Random.int64_in_range" else let span = Int64.succ (Int64.sub max min) in (* Explanation of this test: see comment in [int_in_range_aux]. *) if span <= Int64.zero then int64_in_range_aux s ~min ~max else Int64.add min (int64aux s span) (* Return a [nativeint] between 0 (included) and [bound] (excluded). *) let nativeint = if Nativeint.size = 32 then fun s bound -> Nativeint.of_int32 (int32 s (Nativeint.to_int32 bound)) else fun s bound -> Int64.to_nativeint (int64 s (Int64.of_nativeint bound)) (* Return a [nativeint] between [min] (included) and [max] (included). *) let nativeint_in_range = if Nativeint.size = 32 then fun s ~min ~max -> Nativeint.of_int32 (int32_in_range s ~min:(Nativeint.to_int32 min) ~max:(Nativeint.to_int32 max)) else fun s ~min ~max -> Int64.to_nativeint (int64_in_range s ~min:(Int64.of_nativeint min) ~max:(Int64.of_nativeint max)) (* Returns a float 0 <= x < 1 with at most 90 bits of precision. *) let rawfloat s = let scale = 1073741824.0 and r0 = float_of_int (bits s) and r1 = float_of_int (bits s) and r2 = float_of_int (bits s) in ((r0 /. scale +. r1) /. scale +. r2) /. scale let float s bound = rawfloat s *. bound let bool s = (bits s land 1 = 0) end (* This is the state you get with [init 27182818] on a 32-bit machine. *) let default = { State.st = [| 509760043; 399328820; 99941072; 112282318; 611886020; 516451399; 626288598; 337482183; 748548471; 808894867; 657927153; 386437385; 42355480; 977713532; 311548488; 13857891; 307938721; 93724463; 1041159001; 444711218; 1040610926; 233671814; 664494626; 1071756703; 188709089; 420289414; 969883075; 513442196; 275039308; 918830973; 598627151; 134083417; 823987070; 619204222; 81893604; 871834315; 398384680; 475117924; 520153386; 324637501; 38588599; 435158812; 168033706; 585877294; 328347186; 293179100; 671391820; 846150845; 283985689; 502873302; 718642511; 938465128; 962756406; 107944131; 192910970; |]; State.idx = 0; } let bits () = State.bits default let int bound = State.int default bound let full_int bound = State.full_int default bound let int_in_range ~min ~max = State.int_in_range default ~min ~max let int32 bound = State.int32 default bound let int32_in_range ~min ~max = State.int32_in_range default ~min ~max let nativeint bound = State.nativeint default bound let nativeint_in_range ~min ~max = State.nativeint_in_range default ~min ~max let int64 bound = State.int64 default bound let int64_in_range ~min ~max = State.int64_in_range default ~min ~max let float scale = State.float default scale let bool () = State.bool default let bits32 () = State.bits32 default let bits64 () = State.bits64 default let nativebits () = State.nativebits default let full_init seed = State.full_init default seed let init seed = State.full_init default [| seed |] let self_init () = full_init (random_seed()) (* Manipulating the current state. *) let get_state () = State.copy default let set_state s = State.assign default s (******************** (* Test functions. Not included in the library. The [chisquare] function should be called with n > 10r. It returns a triple (low, actual, high). If low <= actual <= high, the [g] function passed the test, otherwise it failed. Some results: init 27182818; chisquare int 100000 1000 init 27182818; chisquare int 100000 100 init 27182818; chisquare int 100000 5000 init 27182818; chisquare int 1000000 1000 init 27182818; chisquare int 100000 1024 init 299792643; chisquare int 100000 1024 init 14142136; chisquare int 100000 1024 init 27182818; init_diff 1024; chisquare diff 100000 1024 init 27182818; init_diff 100; chisquare diff 100000 100 init 27182818; init_diff2 1024; chisquare diff2 100000 1024 init 27182818; init_diff2 100; chisquare diff2 100000 100 init 14142136; init_diff2 100; chisquare diff2 100000 100 init 299792643; init_diff2 100; chisquare diff2 100000 100 - : float * float * float = (936.754446796632465, 1032., 1063.24555320336754) # - : float * float * float = (80., 91.3699999999953434, 120.) # - : float * float * float = (4858.57864376269026, 4982., 5141.42135623730974) # - : float * float * float = (936.754446796632465, 1017.99399999994785, 1063.24555320336754) # - : float * float * float = (960., 984.565759999997681, 1088.) # - : float * float * float = (960., 1003.40735999999742, 1088.) # - : float * float * float = (960., 1035.23328000000038, 1088.) # - : float * float * float = (960., 1026.79551999999967, 1088.) # - : float * float * float = (80., 110.194000000003143, 120.) # - : float * float * float = (960., 1067.98080000000482, 1088.) # - : float * float * float = (80., 107.292000000001281, 120.) # - : float * float * float = (80., 85.1180000000022119, 120.) # - : float * float * float = (80., 86.614000000001397, 120.) *) (* Return the sum of the squares of v[i0,i1[ *) let rec sumsq v i0 i1 = if i0 >= i1 then 0.0 else if i1 = i0 + 1 then Stdlib.float v.(i0) *. Stdlib.float v.(i0) else sumsq v i0 ((i0+i1)/2) +. sumsq v ((i0+i1)/2) i1 let chisquare g n r = if n <= 10 * r then invalid_arg "chisquare"; let f = Array.make r 0 in for i = 1 to n do let t = g r in f.(t) <- f.(t) + 1 done; let t = sumsq f 0 r and r = Stdlib.float r and n = Stdlib.float n in let sr = 2.0 *. sqrt r in (r -. sr, (r *. t /. n) -. n, r +. sr) (* This is to test for linear dependencies between successive random numbers. *) let st = ref 0 let init_diff r = st := int r let diff r = let x1 = !st and x2 = int r in st := x2; if x1 >= x2 then x1 - x2 else r + x1 - x2 let st1 = ref 0 and st2 = ref 0 (* This is to test for quadratic dependencies between successive random numbers. *) let init_diff2 r = st1 := int r; st2 := int r let diff2 r = let x1 = !st1 and x2 = !st2 and x3 = int r in st1 := x2; st2 := x3; (x3 - x2 - x2 + x1 + 2*r) mod r ********************) stdlib-random-1.2.0/random3/random3.mli000066400000000000000000000205301460153135100176610ustar00rootroot00000000000000(**************************************************************************) (* *) (* OCaml *) (* *) (* Damien Doligez, projet Para, INRIA Rocquencourt *) (* *) (* Copyright 1996 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (** Pseudo-random number generators (PRNG). *) (** {1 Basic functions} *) val init : int -> unit (** Initialize the generator, using the argument as a seed. The same seed will always yield the same sequence of numbers. *) val full_init : int array -> unit (** Same as {!Random3.init} but takes more data as seed. *) val self_init : unit -> unit (** Initialize the generator with a random seed chosen in a system-dependent way. If [/dev/urandom] is available on the host machine, it is used to provide a highly random initial seed. Otherwise, a less random seed is computed from system parameters (current time, process IDs). *) val bits : unit -> int (** Return 30 random bits in a nonnegative integer.*) val int : int -> int (** [Random3.int bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] must be greater than 0 and less than 2{^30}. @raise Invalid_argument if [bound] <= 0 or [bound] >= 2{^30}. *) val full_int : int -> int (** [Random3.full_int bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] may be any positive integer. If [bound] is less than 2{^31}, then [Random3.full_int bound] yields identical output across systems with varying [int] sizes. If [bound] is less than 2{^30}, then [Random3.full_int bound] is equal to {!Random3.int}[ bound]. If [bound] is at least 2{^30} (on 64-bit systems, or non-standard environments such as JavaScript), then [Random3.full_int] returns a value whereas {!Random3.int} raises {!Stdlib.Invalid_argument}. @raise Invalid_argument if [bound] <= 0. @since 4.13 *) val int_in_range : min:int -> max:int -> int (** [Random3.int_in_range ~min ~max] returns a random integer between [min] (inclusive) and [max] (inclusive). Both [min] and [max] are allowed to be negative; [min] must be less than or equal to [max]. If both bounds fit in 32-bit signed integers (that is, if -2{^31} <= [min] and [max] < 2{^31}), then [int_in_range] yields identical output across systems with varying [int] sizes. @raise Invalid_argument if [min > max]. @since 5.2 *) val int32 : Int32.t -> Int32.t (** [Random3.int32 bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] must be greater than 0. @raise Invalid_argument if [bound] <= 0. *) val int32_in_range : min:int32 -> max:int32 -> int32 (** [Random3.int32_in_range ~min ~max] returns a random integer between [min] (inclusive) and [max] (inclusive). Both [min] and [max] are allowed to be negative; [min] must be less than or equal to [max]. @raise Invalid_argument if [min > max]. @since 5.2 *) val nativeint : Nativeint.t -> Nativeint.t (** [Random3.nativeint bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] must be greater than 0. @raise Invalid_argument if [bound] <= 0. *) val nativeint_in_range : min:nativeint -> max:nativeint -> nativeint (** [Random3.nativeint_in_range ~min ~max] returns a random integer between [min] (inclusive) and [max] (inclusive). Both [min] and [max] are allowed to be negative; [min] must be less than or equal to [max]. @raise Invalid_argument if [min > max]. @since 5.2 *) val int64 : Int64.t -> Int64.t (** [Random3.int64 bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] must be greater than 0. @raise Invalid_argument if [bound] <= 0. *) val int64_in_range : min:int64 -> max:int64 -> int64 (** [Random3.int64_in_range ~min ~max] returns a random integer between [min] (inclusive) and [max] (inclusive). Both [min] and [max] are allowed to be negative; [min] must be less than or equal to [max]. @raise Invalid_argument if [min > max]. @since 5.2 *) val float : float -> float (** [Random3.float bound] returns a random floating-point number between 0 and [bound] (inclusive). If [bound] is negative, the result is negative or zero. If [bound] is 0, the result is 0. *) val bool : unit -> bool (** [Random3.bool ()] returns [true] or [false] with probability 0.5 each. *) val bits32 : unit -> Int32.t (** [Random3.bits32 ()] returns 32 random bits as an integer between {!Int32.min_int} and {!Int32.max_int}. *) val bits64 : unit -> Int64.t (** [Random3.bits64 ()] returns 64 random bits as an integer between {!Int64.min_int} and {!Int64.max_int}. @since 4.14 *) val nativebits : unit -> Nativeint.t (** [Random3.nativebits ()] returns 32 or 64 random bits (depending on the bit width of the platform) as an integer between {!Nativeint.min_int} and {!Nativeint.max_int}. @since 4.14 *) (** {1 Advanced functions} *) (** The functions from module {!State} manipulate the current state of the random generator explicitly. This allows using one or several deterministic PRNGs, even in a multi-threaded program, without interference from other parts of the program. *) module State : sig type t (** The type of PRNG states. *) val make : int array -> t (** Create a new state and initialize it with the given seed. *) val make_self_init : unit -> t (** Create a new state and initialize it with a system-dependent low-entropy seed. *) val copy : t -> t (** Return a copy of the given state. *) val bits : t -> int val int : t -> int -> int val full_int : t -> int -> int val int_in_range : t -> min:int -> max:int -> int val int32 : t -> Int32.t -> Int32.t val int32_in_range : t -> min:int32 -> max:int32 -> int32 val nativeint : t -> Nativeint.t -> Nativeint.t val nativeint_in_range : t -> min:nativeint -> max:nativeint -> nativeint val int64 : t -> Int64.t -> Int64.t val int64_in_range : t -> min:int64 -> max:int64 -> int64 val float : t -> float -> float val bool : t -> bool val bits32 : t -> Int32.t val bits64 : t -> Int64.t val nativebits : t -> Nativeint.t (** These functions are the same as the basic functions, except that they use (and update) the given PRNG state instead of the default one. *) val to_binary_string : t -> string (** Serializes the PRNG state into an immutable sequence of bytes. See {!of_binary_string} for deserialization. The [string] type is intended here for serialization only, the encoding is not human-readable and may not be printable. Note that the serialization format may differ across OCaml versions. @since 5.1 *) val of_binary_string : string -> t (** Deserializes a byte sequence obtained by calling {!to_binary_string}. The resulting PRNG state will produce the same random numbers as the state that was passed as input to {!to_binary_string}. @raise Failure if the input is not in the expected format. Note that the serialization format may differ across OCaml versions. Unlike the functions provided by the {!Marshal} module, this function either produces a valid state or fails cleanly with a [Failure] exception. It can be safely used on user-provided, untrusted inputs. @since 5.1 *) end val get_state : unit -> State.t (** Return the current state of the generator used by the basic functions. *) val set_state : State.t -> unit (** Set the state of the generator used by the basic functions. *) stdlib-random-1.2.0/random4/000077500000000000000000000000001460153135100156145ustar00rootroot00000000000000stdlib-random-1.2.0/random4/dune000066400000000000000000000002261460153135100164720ustar00rootroot00000000000000(library (public_name stdlib-random.v4) (name random4) (preprocess (action (run %{bin:cppo} -V OCAML:%{ocaml_version} %{input-file}))) ) stdlib-random-1.2.0/random4/random4.ml000066400000000000000000000472341460153135100175240ustar00rootroot00000000000000(**************************************************************************) (* *) (* OCaml *) (* *) (* Damien Doligez, projet Para, INRIA Rocquencourt *) (* *) (* Copyright 1996 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (* Pseudo-random number generator This is a lagged-Fibonacci F(55, 24, +) with a modified addition function to enhance the mixing of bits. If we use normal addition, the low-order bit fails tests 1 and 7 of the Diehard test suite, and bits 1 and 2 also fail test 7. If we use multiplication as suggested by Marsaglia, it doesn't fare much better. By mixing the bits of one of the numbers before addition (XOR the 5 high-order bits into the low-order bits), we get a generator that passes all the Diehard tests. *) external random_seed: unit -> int array = "caml_sys_random_seed" module State = struct type t = { st : int array; mutable idx : int } let new_state () = { st = Array.make 55 0; idx = 0 } let assign st1 st2 = Array.blit st2.st 0 st1.st 0 55; st1.idx <- st2.idx let serialization_prefix = "lfsr2:" (* "lfsr" denotes the algorithm currently in use, and '2' is a version number. Each Random algorithm or serialization format should have distinct prefix , so that users get a clean error instead of believing that they faithfully reproduce their previous state and in fact get a differrent stream. Note that there is no constraint to keep the same ":" format or message size in future versions, we could change the format completely if we wanted as long as there is no confusion possible with the previous formats. *) let serialization_prefix_len = String.length serialization_prefix (* Compatibility functions Imported from standard library *) #if OCAML_VERSION < (4,13,0) let get_int32_le s off = let res = ref Int32.zero in for i = 3 downto 0 do let v = Int32.of_int (Char.code s.[off+i]) in res := Int32.(add v (shift_left !res 8)) done; !res let get_int8 s off = Char.code s.[off] let starts_with ~prefix s = let open String in let len_s = length s and len_pre = length prefix in let rec aux i = if i = len_pre then true else if unsafe_get s i <> unsafe_get prefix i then false else aux (i + 1) in len_s >= len_pre && aux 0 #else let get_int32_le = String.get_int32_le let get_int8 = String.get_int8 let starts_with = String.starts_with #endif let to_binary_string s = let prefix = serialization_prefix in let preflen = serialization_prefix_len in let buf = Bytes.create (preflen + 55 * 4 + 1) in Bytes.blit_string prefix 0 buf 0 preflen; for i = 0 to 54 do Bytes.set_int32_le buf (preflen + i * 4) (Int32.of_int (s.st.(i) land 0x3FFFFFFF)) done; Bytes.set_int8 buf (preflen + 55 * 4) s.idx; Bytes.unsafe_to_string buf let of_binary_string buf = let prefix = serialization_prefix in let preflen = serialization_prefix_len in if String.length buf <> preflen + 1 + 55 * 4 || not (starts_with ~prefix buf) then failwith ("Random4.State.of_binary_string: expected a format \ compatible with Random4 PRNG"); let st = new_state () in for i=0 to 54 do let n = get_int32_le buf (preflen + i * 4) in st.st.(i) <- Int32.(to_int @@ logand n 0x3FFFFFFFl) done; st.idx <- get_int8 buf (preflen + 55 * 4); st let full_init s seed = let combine accu x = Digest.string (accu ^ Int.to_string x) in let extract d = Char.code d.[0] + (Char.code d.[1] lsl 8) + (Char.code d.[2] lsl 16) + (Char.code d.[3] lsl 24) in let seed = if Array.length seed = 0 then [| 0 |] else seed in let l = Array.length seed in for i = 0 to 54 do s.st.(i) <- i; done; let accu = ref "x" in for i = 0 to 54 + max 55 l do let j = i mod 55 in let k = i mod l in accu := combine !accu seed.(k); s.st.(j) <- (s.st.(j) lxor extract !accu) land 0x3FFFFFFF; (* PR#5575 *) done; s.idx <- 0 let make seed = let result = new_state () in full_init result seed; result let make_self_init () = make (random_seed ()) let copy s = let result = new_state () in assign result s; result let min_int31 = -0x4000_0000 (* = -2{^30}, which is [min_int] for 31-bit integers *) let max_int31 = 0x3FFF_FFFF (* = 2{^30}-1, which is [max_int] for 31-bit integers *) (* avoid integer literals for these, 32-bit OCaml would reject them: *) let min_int32 = -(1 lsl 31) (* = -0x8000_0000 on platforms where [Sys.int_size >= 32] *) let max_int32 = (1 lsl 31) - 1 (* = 0x7FFF_FFFF on platforms where [Sys.int_size >= 32] *) (* Return 30 random bits as an integer 0 <= x < 2^30 *) let bits s = s.idx <- (s.idx + 1) mod 55; let curval = s.st.(s.idx) in let newval = s.st.((s.idx + 24) mod 55) + (curval lxor ((curval lsr 25) land 0x1F)) in let newval30 = newval land 0x3FFFFFFF in (* PR#5575 *) s.st.(s.idx) <- newval30; newval30 let bits32 s = let b1 = Int32.(shift_right_logical (of_int (bits s)) 14) in (* 16 bits *) let b2 = Int32.(shift_right_logical (of_int (bits s)) 14) in (* 16 bits *) Int32.(logor b1 (shift_left b2 16)) let bits64 s = let b1 = Int64.(shift_right_logical (of_int (bits s)) 9) in (* 21 bits *) let b2 = Int64.(shift_right_logical (of_int (bits s)) 9) in (* 21 bits *) let b3 = Int64.(shift_right_logical (of_int (bits s)) 8) in (* 22 bits *) Int64.(logor b1 (logor (shift_left b2 21) (shift_left b3 42))) let rec int31aux s n = let r = bits s in let v = r mod n in if r - v > max_int31 - n + 1 then int31aux s n else v (* Return an integer between 0 (included) and [bound] (excluded). The bound must fit in 31-bit signed integers. This function yields the same output regardless of the integer size. *) let int s bound = if bound > max_int31 || bound <= 0 then invalid_arg "Random.int" else int31aux s bound let rec int63aux s n = let b1 = bits s in let b2 = bits s in let (r, max_int) = if n <= max_int32 then (* 31 random bits on both 64-bit OCaml and JavaScript. Use upper 15 bits of b1 and 16 bits of b2. *) let bpos = (((b2 land 0x3FFFC000) lsl 1) lor (b1 lsr 15)) in (bpos, max_int32) else let b3 = bits s in (* 62 random bits on 64-bit OCaml; unreachable on JavaScript. Use upper 20 bits of b1 and 21 bits of b2 and b3. *) let bpos = ((((b3 land 0x3FFFFE00) lsl 12) lor (b2 lsr 9)) lsl 20) lor (b1 lsr 10) in (bpos, max_int) in let v = r mod n in if r - v > max_int - n + 1 then int63aux s n else v let full_int s bound = if bound <= 0 then invalid_arg "Random.full_int" else if bound > 0x3FFFFFFF then int63aux s bound else int31aux s bound (* Return an integer between 0 (included) and [n] (excluded). [bound] may be any positive [int]. [mask] must be of the form [2{^i}-1] and greater or equal to [n]. Larger values of [mask] make the function run faster (fewer samples are rejected). Smaller values of [mask] are usable on a wider range of OCaml implementations. *) let rec int_aux s n mask = (* We start by drawing a non-negative integer in the [ [0, mask] ] range *) let r = Int64.to_int (bits64 s) land mask in let v = r mod n in (* For uniform distribution of the result between 0 included and [n] * excluded, the random number [r] must have been drawn uniformly in * an interval whose length is a multiple of [n]. To achieve this, * we use rejection sampling on the greatest interval [ [0, k*n-1] ] * that fits in [ [0, mask] ]. That is, we reject the * sample if it falls outside of this interval, and draw again. * This is what the test below does, while carefully avoiding * overflows and sparing a division [mask / n]. *) if r - v > mask - n + 1 then int_aux s n mask else v (* Return an integer between [min] (included) and [max] (included). The [nbits] parameter is the size in bits of the signed integers we draw from [s]. We must have [-2{^nbits - 1} <= min <= max < 2{^nbits - 1}]. Moreover, for the iteration to converge quickly, the interval [[min, max]] should have width at least [2{^nbits - 1}]. As the width approaches this lower limit, the average number of draws approaches 2, with a quite high standard deviation (2 + epsilon). *) let rec int_in_large_range s ~min ~max ~nbits = let drop = Sys.int_size - nbits in (* The bitshifts replicate the [nbits]-th bit (sign bit) to higher bits: *) let r = ((Int64.to_int (bits64 s)) lsl drop) asr drop in if r < min || r > max then int_in_large_range s ~min ~max ~nbits else r (* Return an integer between [min] (included) and [max] (included). [mask] is as described for [int_aux]. [nbits] is as described for [int_in_large_range]. *) let int_in_range_aux s ~min ~max ~mask ~nbits = let span = max - min + 1 in if span <= mask (* [span] is small enough *) && span > 0 (* no overflow occurred when computing [span] *) then (* Just draw a number in [[0, span)] and shift it by [min]. *) min + int_aux s span mask else (* Span too large, use the alternative drawing method. *) int_in_large_range s ~min ~max ~nbits (* 31bits version to account for the 31 bit PRNG *) let rec int31_in_large_range s ~min ~max = let r = Int32.to_int (bits32 s) in if r < min || r > max then int31_in_large_range s ~min ~max else r let int31_in_range_aux s ~min ~max = let mask = max_int31 in let span = max - min + 1 in if span <= mask (* [span] is small enough *) && span > 0 (* no overflow occurred when computing [span] *) then (* Just draw a number in [[0, span)] and shift it by [min]. *) min + int31aux s span else (* Span too large, use the alternative drawing method. *) int31_in_large_range s ~min ~max (* Return an integer between [min] (included) and [max] (included). We must have [min <= max]. *) let int_in_range s ~min ~max = if min > max then invalid_arg "Random.int_in_range"; (* When both bounds fit in 31-bit signed integers, we use parameters [mask] and [nbits] appropriate for 31-bit integers, so as to yield the same output on all platforms supported by OCaml. When both bounds fit in 32-bit signed integers, we use parameters [mask] and [nbits] appropriate for 32-bit integers, so as to yield the same output on JavaScript and on 64-bit OCaml. *) if min >= min_int31 && max <= max_int31 then int31_in_range_aux s ~min ~max else if min >= min_int32 && max <= max_int32 then int_in_range_aux s ~min ~max ~mask:max_int32 ~nbits:32 else int_in_range_aux s ~min ~max ~mask:max_int ~nbits:Sys.int_size let rec int32aux s n = let b1 = Int32.of_int (bits s) in let b2 = Int32.shift_left (Int32.of_int (bits s land 1)) 30 in let r = Int32.logor b1 b2 in let v = Int32.rem r n in if Int32.sub r v > Int32.add (Int32.sub Int32.max_int n) 1l then int32aux s n else v let int32 s bound = if bound <= 0l then invalid_arg "Random.int32" else int32aux s bound (* Return an [int32] between [min] (included) and [max] (included). We must have [min <= max]. *) let rec int32_in_range_aux s ~min ~max = let r = bits32 s in if r < min || r > max then int32_in_range_aux s ~min ~max else r let int32_in_range s ~min ~max = if min > max then invalid_arg "Random.int32_in_range" else let span = Int32.succ (Int32.sub max min) in (* Explanation of this test: see comment in [int_in_range_aux]. *) if span <= Int32.zero then int32_in_range_aux s ~min ~max else Int32.add min (int32aux s span) let rec int64aux s n = let b1 = Int64.of_int (bits s) in let b2 = Int64.shift_left (Int64.of_int (bits s)) 30 in let b3 = Int64.shift_left (Int64.of_int (bits s land 7)) 60 in let r = Int64.logor b1 (Int64.logor b2 b3) in let v = Int64.rem r n in if Int64.sub r v > Int64.add (Int64.sub Int64.max_int n) 1L then int64aux s n else v let int64 s bound = if bound <= 0L then invalid_arg "Random.int64" else int64aux s bound (* Return an [int64] between [min] (included) and [max] (included). We must have [min <= max]. *) let rec int64_in_range_aux s ~min ~max = let r = bits64 s in if r < min || r > max then int64_in_range_aux s ~min ~max else r let int64_in_range s ~min ~max = if min > max then invalid_arg "Random.int64_in_range" else let span = Int64.succ (Int64.sub max min) in (* Explanation of this test: see comment in [int_in_range_aux]. *) if span <= Int64.zero then int64_in_range_aux s ~min ~max else Int64.add min (int64aux s span) (* Return 32 or 64 random bits as a [nativeint] *) let nativebits = if Nativeint.size = 32 then fun s -> Nativeint.of_int32 (bits32 s) else fun s -> Int64.to_nativeint (bits64 s) (* Return a [nativeint] between 0 (included) and [bound] (excluded). *) let nativeint = if Nativeint.size = 32 then fun s bound -> Nativeint.of_int32 (int32 s (Nativeint.to_int32 bound)) else fun s bound -> Int64.to_nativeint (int64 s (Int64.of_nativeint bound)) (* Return a [nativeint] between [min] (included) and [max] (included). *) let nativeint_in_range = if Nativeint.size = 32 then fun s ~min ~max -> Nativeint.of_int32 (int32_in_range s ~min:(Nativeint.to_int32 min) ~max:(Nativeint.to_int32 max)) else fun s ~min ~max -> Int64.to_nativeint (int64_in_range s ~min:(Int64.of_nativeint min) ~max:(Int64.of_nativeint max)) (* Returns a float 0 <= x <= 1 with at most 60 bits of precision. *) let rawfloat s = let scale = 1073741824.0 (* 2^30 *) and r1 = Stdlib.float (bits s) and r2 = Stdlib.float (bits s) in (r1 /. scale +. r2) /. scale let float s bound = rawfloat s *. bound let bool s = (bits s land 1 = 0) end (* This is the state you get with [init 27182818] and then applying the "land 0x3FFFFFFF" filter to them. See #5575, #5793, #5977. *) let default = { State.st = [| 0x3ae2522b; 0x1d8d4634; 0x15b4fad0; 0x18b14ace; 0x12f8a3c4; 0x3b086c47; 0x16d467d6; 0x101d91c7; 0x321df177; 0x0176c193; 0x1ff72bf1; 0x1e889109; 0x0b464b18; 0x2b86b97c; 0x0891da48; 0x03137463; 0x085ac5a1; 0x15d61f2f; 0x3bced359; 0x29c1c132; 0x3a86766e; 0x366d8c86; 0x1f5b6222; 0x3ce1b59f; 0x2ebf78e1; 0x27cd1b86; 0x258f3dc3; 0x389a8194; 0x02e4c44c; 0x18c43f7d; 0x0f6e534f; 0x1e7df359; 0x055d0b7e; 0x10e84e7e; 0x126198e4; 0x0e7722cb; 0x1cbede28; 0x3391b964; 0x3d40e92a; 0x0c59933d; 0x0b8cd0b7; 0x24efff1c; 0x2803fdaa; 0x08ebc72e; 0x0f522e32; 0x05398edc; 0x2144a04c; 0x0aef3cbd; 0x01ad4719; 0x35b93cd6; 0x2a559d4f; 0x1e6fd768; 0x26e27f36; 0x186f18c3; 0x2fbf967a; |]; State.idx = 0; } let bits () = State.bits default let int bound = State.int default bound let full_int bound = State.full_int default bound let int_in_range ~min ~max = State.int_in_range default ~min ~max let int32 bound = State.int32 default bound let int32_in_range ~min ~max = State.int32_in_range default ~min ~max let nativeint bound = State.nativeint default bound let nativeint_in_range ~min ~max = State.nativeint_in_range default ~min ~max let int64 bound = State.int64 default bound let int64_in_range ~min ~max = State.int64_in_range default ~min ~max let float scale = State.float default scale let bool () = State.bool default let bits32 () = State.bits32 default let bits64 () = State.bits64 default let nativebits () = State.nativebits default let full_init seed = State.full_init default seed let init seed = State.full_init default [| seed |] let self_init () = full_init (random_seed()) (* Manipulating the current state. *) let get_state () = State.copy default let set_state s = State.assign default s (******************** (* Test functions. Not included in the library. The [chisquare] function should be called with n > 10r. It returns a triple (low, actual, high). If low <= actual <= high, the [g] function passed the test, otherwise it failed. Some results: init 27182818; chisquare int 100000 1000 init 27182818; chisquare int 100000 100 init 27182818; chisquare int 100000 5000 init 27182818; chisquare int 1000000 1000 init 27182818; chisquare int 100000 1024 init 299792643; chisquare int 100000 1024 init 14142136; chisquare int 100000 1024 init 27182818; init_diff 1024; chisquare diff 100000 1024 init 27182818; init_diff 100; chisquare diff 100000 100 init 27182818; init_diff2 1024; chisquare diff2 100000 1024 init 27182818; init_diff2 100; chisquare diff2 100000 100 init 14142136; init_diff2 100; chisquare diff2 100000 100 init 299792643; init_diff2 100; chisquare diff2 100000 100 - : float * float * float = (936.754446796632465, 997.5, 1063.24555320336754) # - : float * float * float = (80., 89.7400000000052387, 120.) # - : float * float * float = (4858.57864376269, 5045.5, 5141.42135623731) # - : float * float * float = (936.754446796632465, 944.805999999982305, 1063.24555320336754) # - : float * float * float = (960., 1019.19744000000355, 1088.) # - : float * float * float = (960., 1059.31776000000536, 1088.) # - : float * float * float = (960., 1039.98463999999512, 1088.) # - : float * float * float = (960., 1054.38207999999577, 1088.) # - : float * float * float = (80., 90.096000000005, 120.) # - : float * float * float = (960., 1076.78720000000612, 1088.) # - : float * float * float = (80., 85.1760000000067521, 120.) # - : float * float * float = (80., 85.2160000000003492, 120.) # - : float * float * float = (80., 80.6220000000030268, 120.) *) (* Return the sum of the squares of v[i0,i1[ *) let rec sumsq v i0 i1 = if i0 >= i1 then 0.0 else if i1 = i0 + 1 then Stdlib.float v.(i0) *. Stdlib.float v.(i0) else sumsq v i0 ((i0+i1)/2) +. sumsq v ((i0+i1)/2) i1 let chisquare g n r = if n <= 10 * r then invalid_arg "chisquare"; let f = Array.make r 0 in for i = 1 to n do let t = g r in f.(t) <- f.(t) + 1 done; let t = sumsq f 0 r and r = Stdlib.float r and n = Stdlib.float n in let sr = 2.0 *. sqrt r in (r -. sr, (r *. t /. n) -. n, r +. sr) (* This is to test for linear dependencies between successive random numbers. *) let st = ref 0 let init_diff r = st := int r let diff r = let x1 = !st and x2 = int r in st := x2; if x1 >= x2 then x1 - x2 else r + x1 - x2 let st1 = ref 0 and st2 = ref 0 (* This is to test for quadratic dependencies between successive random numbers. *) let init_diff2 r = st1 := int r; st2 := int r let diff2 r = let x1 = !st1 and x2 = !st2 and x3 = int r in st1 := x2; st2 := x3; (x3 - x2 - x2 + x1 + 2*r) mod r ********************) stdlib-random-1.2.0/random4/random4.mli000066400000000000000000000205301460153135100176630ustar00rootroot00000000000000(**************************************************************************) (* *) (* OCaml *) (* *) (* Damien Doligez, projet Para, INRIA Rocquencourt *) (* *) (* Copyright 1996 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (** Pseudo-random number generators (PRNG). *) (** {1 Basic functions} *) val init : int -> unit (** Initialize the generator, using the argument as a seed. The same seed will always yield the same sequence of numbers. *) val full_init : int array -> unit (** Same as {!Random4.init} but takes more data as seed. *) val self_init : unit -> unit (** Initialize the generator with a random seed chosen in a system-dependent way. If [/dev/urandom] is available on the host machine, it is used to provide a highly random initial seed. Otherwise, a less random seed is computed from system parameters (current time, process IDs). *) val bits : unit -> int (** Return 30 random bits in a nonnegative integer.*) val int : int -> int (** [Random4.int bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] must be greater than 0 and less than 2{^30}. @raise Invalid_argument if [bound] <= 0 or [bound] >= 2{^30}. *) val full_int : int -> int (** [Random4.full_int bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] may be any positive integer. If [bound] is less than 2{^31}, then [Random4.full_int bound] yields identical output across systems with varying [int] sizes. If [bound] is less than 2{^30}, then [Random4.full_int bound] is equal to {!Random4.int}[ bound]. If [bound] is at least 2{^30} (on 64-bit systems, or non-standard environments such as JavaScript), then [Random4.full_int] returns a value whereas {!Random4.int} raises {!Stdlib.Invalid_argument}. @raise Invalid_argument if [bound] <= 0. @since 4.13 *) val int_in_range : min:int -> max:int -> int (** [Random4.int_in_range ~min ~max] returns a random integer between [min] (inclusive) and [max] (inclusive). Both [min] and [max] are allowed to be negative; [min] must be less than or equal to [max]. If both bounds fit in 32-bit signed integers (that is, if -2{^31} <= [min] and [max] < 2{^31}), then [int_in_range] yields identical output across systems with varying [int] sizes. @raise Invalid_argument if [min > max]. @since 5.2 *) val int32 : Int32.t -> Int32.t (** [Random4.int32 bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] must be greater than 0. @raise Invalid_argument if [bound] <= 0. *) val int32_in_range : min:int32 -> max:int32 -> int32 (** [Random4.int32_in_range ~min ~max] returns a random integer between [min] (inclusive) and [max] (inclusive). Both [min] and [max] are allowed to be negative; [min] must be less than or equal to [max]. @raise Invalid_argument if [min > max]. @since 5.2 *) val nativeint : Nativeint.t -> Nativeint.t (** [Random4.nativeint bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] must be greater than 0. @raise Invalid_argument if [bound] <= 0. *) val nativeint_in_range : min:nativeint -> max:nativeint -> nativeint (** [Random4.nativeint_in_range ~min ~max] returns a random integer between [min] (inclusive) and [max] (inclusive). Both [min] and [max] are allowed to be negative; [min] must be less than or equal to [max]. @raise Invalid_argument if [min > max]. @since 5.2 *) val int64 : Int64.t -> Int64.t (** [Random4.int64 bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] must be greater than 0. @raise Invalid_argument if [bound] <= 0. *) val int64_in_range : min:int64 -> max:int64 -> int64 (** [Random4.int64_in_range ~min ~max] returns a random integer between [min] (inclusive) and [max] (inclusive). Both [min] and [max] are allowed to be negative; [min] must be less than or equal to [max]. @raise Invalid_argument if [min > max]. @since 5.2 *) val float : float -> float (** [Random4.float bound] returns a random floating-point number between 0 and [bound] (inclusive). If [bound] is negative, the result is negative or zero. If [bound] is 0, the result is 0. *) val bool : unit -> bool (** [Random4.bool ()] returns [true] or [false] with probability 0.5 each. *) val bits32 : unit -> Int32.t (** [Random4.bits32 ()] returns 32 random bits as an integer between {!Int32.min_int} and {!Int32.max_int}. *) val bits64 : unit -> Int64.t (** [Random4.bits64 ()] returns 64 random bits as an integer between {!Int64.min_int} and {!Int64.max_int}. @since 4.14 *) val nativebits : unit -> Nativeint.t (** [Random4.nativebits ()] returns 32 or 64 random bits (depending on the bit width of the platform) as an integer between {!Nativeint.min_int} and {!Nativeint.max_int}. @since 4.14 *) (** {1 Advanced functions} *) (** The functions from module {!State} manipulate the current state of the random generator explicitly. This allows using one or several deterministic PRNGs, even in a multi-threaded program, without interference from other parts of the program. *) module State : sig type t (** The type of PRNG states. *) val make : int array -> t (** Create a new state and initialize it with the given seed. *) val make_self_init : unit -> t (** Create a new state and initialize it with a system-dependent low-entropy seed. *) val copy : t -> t (** Return a copy of the given state. *) val bits : t -> int val int : t -> int -> int val full_int : t -> int -> int val int_in_range : t -> min:int -> max:int -> int val int32 : t -> Int32.t -> Int32.t val int32_in_range : t -> min:int32 -> max:int32 -> int32 val nativeint : t -> Nativeint.t -> Nativeint.t val nativeint_in_range : t -> min:nativeint -> max:nativeint -> nativeint val int64 : t -> Int64.t -> Int64.t val int64_in_range : t -> min:int64 -> max:int64 -> int64 val float : t -> float -> float val bool : t -> bool val bits32 : t -> Int32.t val bits64 : t -> Int64.t val nativebits : t -> Nativeint.t (** These functions are the same as the basic functions, except that they use (and update) the given PRNG state instead of the default one. *) val to_binary_string : t -> string (** Serializes the PRNG state into an immutable sequence of bytes. See {!of_binary_string} for deserialization. The [string] type is intended here for serialization only, the encoding is not human-readable and may not be printable. Note that the serialization format may differ across OCaml versions. @since 5.1 *) val of_binary_string : string -> t (** Deserializes a byte sequence obtained by calling {!to_binary_string}. The resulting PRNG state will produce the same random numbers as the state that was passed as input to {!to_binary_string}. @raise Failure if the input is not in the expected format. Note that the serialization format may differ across OCaml versions. Unlike the functions provided by the {!Marshal} module, this function either produces a valid state or fails cleanly with a [Failure] exception. It can be safely used on user-provided, untrusted inputs. @since 5.1 *) end val get_state : unit -> State.t (** Return the current state of the generator used by the basic functions. *) val set_state : State.t -> unit (** Set the state of the generator used by the basic functions. *) stdlib-random-1.2.0/random5/000077500000000000000000000000001460153135100156155ustar00rootroot00000000000000stdlib-random-1.2.0/random5/dune000066400000000000000000000002731460153135100164750ustar00rootroot00000000000000(library (public_name stdlib-random.v5) (name random5) (foreign_stubs (language c) (names prng)) (preprocess (action (run %{bin:cppo} -V OCAML:%{ocaml_version} %{input-file}))) ) stdlib-random-1.2.0/random5/prng.c000066400000000000000000000052601460153135100167320ustar00rootroot00000000000000/**************************************************************************/ /* */ /* OCaml */ /* */ /* Xavier Leroy, projet Cambium, College de France and Inria */ /* */ /* Copyright 2021 Institut National de Recherche en Informatique et */ /* en Automatique. */ /* */ /* All rights reserved. This file is distributed under the terms of */ /* the GNU Lesser General Public License version 2.1, with the */ /* special exception on linking described in the file LICENSE. */ /* */ /**************************************************************************/ #include #include "caml/alloc.h" #include "caml/bigarray.h" #include "caml/mlvalues.h" /* The L64X128 member of the LXM family. Taken from figure 1 in "LXM: Better Splittable Pseudorandom Number Generators (and Almost as Fast)" by Guy L. Steele Jr. and Sebastiano Vigna, OOPSLA 2021. */ static const uint64_t M = 0xd1342543de82ef95; struct LXM_state { uint64_t a; /* per-instance additive parameter (odd) */ uint64_t s; /* state of the LCG subgenerator */ uint64_t x[2]; /* state of the XBG subgenerator (not 0) */ }; /* In OCaml, states are represented as a 1D big array of 64-bit integers */ #define LXM_val(v) ((struct LXM_state *) Caml_ba_data_val(v)) #ifndef Caml_inline // Define Caml_inline for OCaml <= 4.12 #if defined(_MSC_VER) && !defined(__cplusplus) #define Caml_inline static __inline #else #define Caml_inline static inline #endif #endif Caml_inline uint64_t rotl(const uint64_t x, int k) { return (x << k) | (x >> (64 - k)); } CAMLprim uint64_t caml_lxm_next_unboxed(value v) { uint64_t z, q0, q1; struct LXM_state * st = LXM_val(v); /* Combining operation */ z = st->s + st->x[0]; /* Mixing function */ z = (z ^ (z >> 32)) * 0xdaba0b6eb09322e3; z = (z ^ (z >> 32)) * 0xdaba0b6eb09322e3; z = (z ^ (z >> 32)); /* LCG update */ st->s = st->s * M + st->a; /* XBG update */ q0 = st->x[0]; q1 = st->x[1]; q1 ^= q0; q0 = rotl(q0, 24); q0 = q0 ^ q1 ^ (q1 << 16); q1 = rotl(q1, 37); st->x[0] = q0; st->x[1] = q1; /* Return result */ return z; } CAMLprim value caml_lxm_next(value v) { return caml_copy_int64(caml_lxm_next_unboxed(v)); } stdlib-random-1.2.0/random5/random5.ml000066400000000000000000000414331460153135100175210ustar00rootroot00000000000000(**************************************************************************) (* *) (* OCaml *) (* *) (* Damien Doligez, projet Para, INRIA Rocquencourt *) (* Xavier Leroy, projet Cambium, College de France and Inria *) (* *) (* Copyright 1996 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (* Pseudo-random number generator *) external random_seed: unit -> int array = "caml_sys_random_seed" module State = struct open Bigarray type t = (int64, int64_elt, c_layout) Array1.t external next: t -> (int64[@unboxed]) = "caml_lxm_next" "caml_lxm_next_unboxed" [@@noalloc] let create () : t = Array1.create Int64 C_layout 4 let set s i1 i2 i3 i4 = Array1.unsafe_set s 0 (Int64.logor i1 1L); (* must be odd *) Array1.unsafe_set s 1 i2; Array1.unsafe_set s 2 (if i3 <> 0L then i3 else 1L); (* must not be 0 *) Array1.unsafe_set s 3 (if i4 <> 0L then i4 else 2L) (* must not be 0 *) let mk i1 i2 i3 i4 = let s = create () in set s i1 i2 i3 i4; s let serialization_prefix = "lxm1:" (* "lxm" denotes the algorithm currently in use, and '1' is a version number. We should update this prefix if we change the Random algorithm or the serialization format, so that users get a clean error instead of believing that they faithfully reproduce their previous state and in fact get a different stream. Note that there is no constraint to keep the same ":" format or message size in future versions, we could change the format completely if we wanted as long as there is no confusion possible with the previous formats. *) let serialization_prefix_len = String.length serialization_prefix let to_binary_string s = let prefix = serialization_prefix in let preflen = serialization_prefix_len in let buf = Bytes.create (preflen + 4 * 8) in Bytes.blit_string prefix 0 buf 0 preflen; for i = 0 to 3 do Bytes.set_int64_le buf (preflen + i * 8) (Array1.get s i) done; Bytes.unsafe_to_string buf (* Compatibility functions Imported from standard library *) #if OCAML_VERSION < (4,8,0) let set_int64_le b off n = let n = ref n in for i = 0 to 7 do Bytes.set b (off+i) Int64.(Char.unsafe_chr @@ Int64.to_int @@ logand !n 0xFFL); n := Int64.(shift_right !n 8) done #else let set_int64_le = Bytes.set_int64_le #endif #if OCAML_VERSION < (4,13,0) let get_int64_le s off = let res = ref Int64.zero in for i = 7 downto 0 do let v = Int64.of_int (Char.code s.[off+i]) in res := Int64.(add v (shift_left !res 8)) done; !res let starts_with ~prefix s = let open String in let len_s = length s and len_pre = length prefix in let rec aux i = if i = len_pre then true else if unsafe_get s i <> unsafe_get prefix i then false else aux (i + 1) in len_s >= len_pre && aux 0 #else let get_int64_le = String.get_int64_le let starts_with = String.starts_with #endif let of_binary_string buf = let prefix = serialization_prefix in let preflen = serialization_prefix_len in if String.length buf <> preflen + 4 * 8 || not (starts_with ~prefix buf) then failwith ("Random.State.of_binary_string: expected a format \ compatible with OCaml " ^ Sys.ocaml_version); let i1 = get_int64_le buf (preflen + 0 * 8) in let i2 = get_int64_le buf (preflen + 1 * 8) in let i3 = get_int64_le buf (preflen + 2 * 8) in let i4 = get_int64_le buf (preflen + 3 * 8) in mk i1 i2 i3 i4 let assign (dst: t) (src: t) = Array1.blit src dst let copy s = let s' = create() in assign s' s; s' (* The seed is an array of integers. It can be just one integer, but it can also be 12 or more bytes. To hide the difference, we serialize the array as a sequence of bytes, then hash the sequence with MD5 (Digest.bytes). MD5 gives only 128 bits while we need 256 bits, so we hash twice with different suffixes. *) let reinit s seed = let n = Array.length seed in let b = Bytes.create (n * 8 + 1) in for i = 0 to n-1 do set_int64_le b (i * 8) (Int64.of_int seed.(i)) done; Bytes.set b (n * 8) '\x01'; let d1 = Digest.bytes b in Bytes.set b (n * 8) '\x02'; let d2 = Digest.bytes b in set s (get_int64_le d1 0) (get_int64_le d1 8) (get_int64_le d2 0) (get_int64_le d2 8) let make seed = let s = create() in reinit s seed; s let make_self_init () = make (random_seed ()) let min_int31 = -0x4000_0000 (* = -2{^30}, which is [min_int] for 31-bit integers *) let max_int31 = 0x3FFF_FFFF (* = 2{^30}-1, which is [max_int] for 31-bit integers *) (* avoid integer literals for these, 32-bit OCaml would reject them: *) let min_int32 = -(1 lsl 31) (* = -0x8000_0000 on platforms where [Sys.int_size >= 32] *) let max_int32 = (1 lsl 31) - 1 (* = 0x7FFF_FFFF on platforms where [Sys.int_size >= 32] *) (* Return 30 random bits as an integer 0 <= x < 2^30 *) let bits s = Int64.to_int (next s) land max_int31 (* Return an integer between 0 (included) and [n] (excluded). [bound] may be any positive [int]. [mask] must be of the form [2{^i}-1] and greater or equal to [n]. Larger values of [mask] make the function run faster (fewer samples are rejected). Smaller values of [mask] are usable on a wider range of OCaml implementations. *) let rec int_aux s n mask = (* We start by drawing a non-negative integer in the [ [0, mask] ] range *) let r = Int64.to_int (next s) land mask in let v = r mod n in (* For uniform distribution of the result between 0 included and [n] * excluded, the random number [r] must have been drawn uniformly in * an interval whose length is a multiple of [n]. To achieve this, * we use rejection sampling on the greatest interval [ [0, k*n-1] ] * that fits in [ [0, mask] ]. That is, we reject the * sample if it falls outside of this interval, and draw again. * This is what the test below does, while carefully avoiding * overflows and sparing a division [mask / n]. *) if r - v > mask - n + 1 then int_aux s n mask else v (* Return an integer between 0 (included) and [bound] (excluded). The bound must fit in 31-bit signed integers. This function yields the same output regardless of the integer size. *) let int s bound = if bound > max_int31 || bound <= 0 then invalid_arg "Random.int" else int_aux s bound max_int31 (* Return an integer between 0 (included) and [bound] (excluded). [bound] may be any positive [int]. *) let full_int s bound = if bound <= 0 then invalid_arg "Random.full_int" (* When the bound fits in 31-bit signed integers, we use the same mask as in function [int] so as to yield the same output on all platforms supported by OCaml (32-bit OCaml, 64-bit OCaml, and JavaScript). When the bound fits in 32-bit signed integers, we use [max_int32] as the mask so as to yield the same output on all platforms where [Sys.int_size >= 32] (i.e. JavaScript and 64-bit OCaml). *) else int_aux s bound (if bound <= max_int31 then max_int31 else if bound <= max_int32 then max_int32 else max_int) (* Return an integer between [min] (included) and [max] (included). The [nbits] parameter is the size in bits of the signed integers we draw from [s]. We must have [-2{^nbits - 1} <= min <= max < 2{^nbits - 1}]. Moreover, for the iteration to converge quickly, the interval [[min, max]] should have width at least [2{^nbits - 1}]. As the width approaches this lower limit, the average number of draws approaches 2, with a quite high standard deviation (2 + epsilon). *) let rec int_in_large_range s ~min ~max ~nbits = let drop = Sys.int_size - nbits in (* The bitshifts replicate the [nbits]-th bit (sign bit) to higher bits: *) let r = ((Int64.to_int (next s)) lsl drop) asr drop in if r < min || r > max then int_in_large_range s ~min ~max ~nbits else r (* Return an integer between [min] (included) and [max] (included). [mask] is as described for [int_aux]. [nbits] is as described for [int_in_large_range]. *) let int_in_range_aux s ~min ~max ~mask ~nbits = let span = max - min + 1 in if span <= mask (* [span] is small enough *) && span > 0 (* no overflow occurred when computing [span] *) then (* Just draw a number in [[0, span)] and shift it by [min]. *) min + int_aux s span mask else (* Span too large, use the alternative drawing method. *) int_in_large_range s ~min ~max ~nbits (* Return an integer between [min] (included) and [max] (included). We must have [min <= max]. *) let int_in_range s ~min ~max = if min > max then invalid_arg "Random.int_in_range"; (* When both bounds fit in 31-bit signed integers, we use parameters [mask] and [nbits] appropriate for 31-bit integers, so as to yield the same output on all platforms supported by OCaml. When both bounds fit in 32-bit signed integers, we use parameters [mask] and [nbits] appropriate for 32-bit integers, so as to yield the same output on JavaScript and on 64-bit OCaml. *) if min >= min_int31 && max <= max_int31 then int_in_range_aux s ~min ~max ~mask:max_int31 ~nbits:31 else if min >= min_int32 && max <= max_int32 then int_in_range_aux s ~min ~max ~mask:max_int32 ~nbits:32 else int_in_range_aux s ~min ~max ~mask:max_int ~nbits:Sys.int_size (* Return 32 random bits as an [int32] *) let bits32 s = Int64.to_int32 (next s) (* Return an [int32] between 0 (included) and [bound] (excluded). *) let rec int32aux s n = let r = Int32.shift_right_logical (bits32 s) 1 in let v = Int32.rem r n in (* Explanation of this test: see comment in [int_aux]. *) if Int32.(sub r v > add (sub max_int n) 1l) then int32aux s n else v let int32 s bound = if bound <= 0l then invalid_arg "Random.int32" else int32aux s bound (* Return an [int32] between [min] (included) and [max] (included). We must have [min <= max]. *) let rec int32_in_range_aux s ~min ~max = let r = Int64.to_int32 (next s) in if r < min || r > max then int32_in_range_aux s ~min ~max else r let int32_in_range s ~min ~max = if min > max then invalid_arg "Random.int32_in_range" else let span = Int32.succ (Int32.sub max min) in (* Explanation of this test: see comment in [int_in_range_aux]. *) if span <= Int32.zero then int32_in_range_aux s ~min ~max else Int32.add min (int32aux s span) (* Return 64 random bits as an [int64] *) let bits64 s = next s (* Return an [int64] between 0 (included) and [bound] (excluded). *) let rec int64aux s n = let r = Int64.shift_right_logical (bits64 s) 1 in let v = Int64.rem r n in (* Explanation of this test: see comment in [int_aux]. *) if Int64.(sub r v > add (sub max_int n) 1L) then int64aux s n else v let int64 s bound = if bound <= 0L then invalid_arg "Random.int64" else int64aux s bound (* Return an [int64] between [min] (included) and [max] (included). We must have [min <= max]. *) let rec int64_in_range_aux s ~min ~max = let r = next s in if r < min || r > max then int64_in_range_aux s ~min ~max else r let int64_in_range s ~min ~max = if min > max then invalid_arg "Random.int64_in_range" else let span = Int64.succ (Int64.sub max min) in (* Explanation of this test: see comment in [int_in_range_aux]. *) if span <= Int64.zero then int64_in_range_aux s ~min ~max else Int64.add min (int64aux s span) (* Return 32 or 64 random bits as a [nativeint] *) let nativebits = if Nativeint.size = 32 then fun s -> Nativeint.of_int32 (bits32 s) else fun s -> Int64.to_nativeint (bits64 s) (* Return a [nativeint] between 0 (included) and [bound] (excluded). *) let nativeint = if Nativeint.size = 32 then fun s bound -> Nativeint.of_int32 (int32 s (Nativeint.to_int32 bound)) else fun s bound -> Int64.to_nativeint (int64 s (Int64.of_nativeint bound)) (* Return a [nativeint] between [min] (included) and [max] (included). *) let nativeint_in_range = if Nativeint.size = 32 then fun s ~min ~max -> Nativeint.of_int32 (int32_in_range s ~min:(Nativeint.to_int32 min) ~max:(Nativeint.to_int32 max)) else fun s ~min ~max -> Int64.to_nativeint (int64_in_range s ~min:(Int64.of_nativeint min) ~max:(Int64.of_nativeint max)) (* Return a float 0 < x < 1 uniformly distributed among the multiples of 2^-53 *) let rec rawfloat s = let b = next s in let n = Int64.shift_right_logical b 11 in if n <> 0L then Int64.to_float n *. 0x1.p-53 else rawfloat s (* Return a float between 0 and [bound] *) let float s bound = rawfloat s *. bound (* Return a random Boolean *) let bool s = next s < 0L (* Split a new PRNG off the given PRNG *) let split s = let i1 = bits64 s in let i2 = bits64 s in let i3 = bits64 s in let i4 = bits64 s in mk i1 i2 i3 i4 end let mk_default () = (* This is the state obtained with [State.make [| 314159265 |]]. *) State.mk (-6196874289567705097L) 586573249833713189L (-8591268803865043407L) 6388613595849772044L #if OCAML_VERSION < (5,0,0) let random_key = mk_default () let bits () = State.bits random_key let int bound = State.int random_key bound let int_in_range ~min ~max = State.int_in_range random_key ~min ~max let full_int bound = State.full_int random_key bound let int32 bound = State.int32 random_key bound let int32_in_range ~min ~max = State.int32_in_range random_key ~min ~max let nativeint bound = State.nativeint random_key bound let nativeint_in_range ~min ~max = State.nativeint_in_range random_key ~min ~max let int64 bound = State.int64 random_key bound let int64_in_range ~min ~max = State.int64_in_range random_key ~min ~max let float scale = State.float random_key scale let bool () = State.bool random_key let bits32 () = State.bits32 random_key let bits64 () = State.bits64 random_key let nativebits () = State.nativebits random_key let full_init seed = State.reinit random_key seed let init seed = full_init [| seed |] let self_init () = full_init (random_seed()) (* Splitting *) let split () = State.split random_key (* Manipulating the current state. *) let get_state () = State.copy random_key let set_state s = State.assign random_key s #else let random_key = Domain.DLS.new_key ~split_from_parent:State.split mk_default let bits () = State.bits (Domain.DLS.get random_key) let int bound = State.int (Domain.DLS.get random_key) bound let full_int bound = State.full_int (Domain.DLS.get random_key) bound let int_in_range ~min ~max = State.int_in_range (Domain.DLS.get random_key) ~min ~max let int32 bound = State.int32 (Domain.DLS.get random_key) bound let int32_in_range ~min ~max = State.int32_in_range (Domain.DLS.get random_key) ~min ~max let nativeint bound = State.nativeint (Domain.DLS.get random_key) bound let nativeint_in_range ~min ~max = State.nativeint_in_range (Domain.DLS.get random_key) ~min ~max let int64 bound = State.int64 (Domain.DLS.get random_key) bound let int64_in_range ~min ~max = State.int64_in_range (Domain.DLS.get random_key) ~min ~max let float scale = State.float (Domain.DLS.get random_key) scale let bool () = State.bool (Domain.DLS.get random_key) let bits32 () = State.bits32 (Domain.DLS.get random_key) let bits64 () = State.bits64 (Domain.DLS.get random_key) let nativebits () = State.nativebits (Domain.DLS.get random_key) let full_init seed = State.reinit (Domain.DLS.get random_key) seed let init seed = full_init [| seed |] let self_init () = full_init (random_seed()) (* Splitting *) let split () = State.split (Domain.DLS.get random_key) (* Manipulating the current state. *) let get_state () = State.copy (Domain.DLS.get random_key) let set_state s = State.assign (Domain.DLS.get random_key) s #endif stdlib-random-1.2.0/random5/random5.mli000066400000000000000000000234551460153135100176760ustar00rootroot00000000000000(**************************************************************************) (* *) (* OCaml *) (* *) (* Damien Doligez, projet Para, INRIA Rocquencourt *) (* Xavier Leroy, projet Cambium, College de France and Inria *) (* *) (* Copyright 1996 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (** Pseudo-random number generators (PRNG). {1 Concurrency-safety with OCaml 5 } With multiple domains, each domain has its own generator that evolves independently of the generators of other domains. When a domain is created, its generator is initialized by splitting the state of the generator associated with the parent domain. In contrast, all threads within a domain share the same domain-local generator. Independent generators can be created with the {!Random5.split} function and used with the functions from the {!Random5.State} module. *) (** {1 Basic functions} *) val init : int -> unit (** Initialize the domain-local generator, using the argument as a seed. The same seed will always yield the same sequence of numbers. *) val full_init : int array -> unit (** Same as {!Random5.init} but takes more data as seed. *) val self_init : unit -> unit (** Initialize the domain-local generator with a random seed chosen in a system-dependent way. If [/dev/urandom] is available on the host machine, it is used to provide a highly random initial seed. Otherwise, a less random seed is computed from system parameters (current time, process IDs, domain-local state). *) val bits : unit -> int (** Return 30 random bits in a nonnegative integer. *) val int : int -> int (** [Random5.int bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] must be greater than 0 and less than 2{^30}. @raise Invalid_argument if [bound] <= 0 or [bound] >= 2{^30}. *) val full_int : int -> int (** [Random5.full_int bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] may be any positive integer. If [bound] is less than 2{^31}, then [Random.full_int bound] yields identical output across systems with varying [int] sizes. If [bound] is less than 2{^30}, then [Random.full_int bound] is equal to {!Random.int}[ bound]. If [bound] is at least 2{^30} (on 64-bit systems, or non-standard environments such as JavaScript), then [Random.full_int] returns a value whereas {!Random.int} raises {!Stdlib.Invalid_argument}. @raise Invalid_argument if [bound] <= 0. @since 4.13 *) val int_in_range : min:int -> max:int -> int (** [Random5.int_in_range ~min ~max] returns a random integer between [min] (inclusive) and [max] (inclusive). Both [min] and [max] are allowed to be negative; [min] must be less than or equal to [max]. If both bounds fit in 32-bit signed integers (that is, if -2{^31} <= [min] and [max] < 2{^31}), then [int_in_range] yields identical output across systems with varying [int] sizes. @raise Invalid_argument if [min > max]. @since 5.2 *) val int32 : Int32.t -> Int32.t (** [Random5.int32 bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] must be greater than 0. @raise Invalid_argument if [bound] <= 0. *) val int32_in_range : min:int32 -> max:int32 -> int32 (** [Random5.int32_in_range ~min ~max] returns a random integer between [min] (inclusive) and [max] (inclusive). Both [min] and [max] are allowed to be negative; [min] must be less than or equal to [max]. @raise Invalid_argument if [min > max]. @since 5.2 *) val nativeint : Nativeint.t -> Nativeint.t (** [Random5.nativeint bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] must be greater than 0. @raise Invalid_argument if [bound] <= 0. *) val nativeint_in_range : min:nativeint -> max:nativeint -> nativeint (** [Random5.nativeint_in_range ~min ~max] returns a random integer between [min] (inclusive) and [max] (inclusive). Both [min] and [max] are allowed to be negative; [min] must be less than or equal to [max]. @raise Invalid_argument if [min > max]. @since 5.2 *) val int64 : Int64.t -> Int64.t (** [Random5.int64 bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] must be greater than 0. @raise Invalid_argument if [bound] <= 0. *) val int64_in_range : min:int64 -> max:int64 -> int64 (** [Random.int64_in_range ~min ~max] returns a random integer between [min] (inclusive) and [max] (inclusive). Both [min] and [max] are allowed to be negative; [min] must be less than or equal to [max]. @raise Invalid_argument if [min > max]. @since 5.2 *) val float : float -> float (** [Random5.float bound] returns a random floating-point number between 0 and [bound] (inclusive). If [bound] is negative, the result is negative or zero. If [bound] is 0, the result is 0. *) val bool : unit -> bool (** [Random5.bool ()] returns [true] or [false] with probability 0.5 each. *) val bits32 : unit -> Int32.t (** [Random5.bits32 ()] returns 32 random bits as an integer between {!Int32.min_int} and {!Int32.max_int}. *) val bits64 : unit -> Int64.t (** [Random5.bits64 ()] returns 64 random bits as an integer between {!Int64.min_int} and {!Int64.max_int}. @since 4.14 *) val nativebits : unit -> Nativeint.t (** [Random5.nativebits ()] returns 32 or 64 random bits (depending on the bit width of the platform) as an integer between {!Nativeint.min_int} and {!Nativeint.max_int}. @since 4.14 *) (** {1 Advanced functions} *) (** The functions from module {!State} manipulate the current state of the random generator explicitly. This allows using one or several deterministic PRNGs, even in a multi-threaded program, without interference from other parts of the program. *) module State : sig type t (** The type of PRNG states. *) val make : int array -> t (** Create a new state and initialize it with the given seed. *) val make_self_init : unit -> t (** Create a new state and initialize it with a random seed chosen in a system-dependent way. The seed is obtained as described in {!Random5.self_init}. *) val copy : t -> t (** Return a copy of the given state. *) val bits : t -> int val int : t -> int -> int val full_int : t -> int -> int val int_in_range : t -> min:int -> max:int -> int val int32 : t -> Int32.t -> Int32.t val int32_in_range : t -> min:int32 -> max:int32 -> int32 val nativeint : t -> Nativeint.t -> Nativeint.t val nativeint_in_range : t -> min:nativeint -> max:nativeint -> nativeint val int64 : t -> Int64.t -> Int64.t val int64_in_range : t -> min:int64 -> max:int64 -> int64 val float : t -> float -> float val bool : t -> bool val bits32 : t -> Int32.t val bits64 : t -> Int64.t val nativebits : t -> Nativeint.t (** These functions are the same as the basic functions, except that they use (and update) the given PRNG state instead of the default one. *) val split : t -> t (** Draw a fresh PRNG state from the given PRNG state. (The given PRNG state is modified.) The new PRNG is statistically independent from the given PRNG. Data can be drawn from both PRNGs, in any order, without risk of correlation. Both PRNGs can be split later, arbitrarily many times. @since 5.0 *) val to_binary_string : t -> string (** Serializes the PRNG state into an immutable sequence of bytes. See {!of_binary_string} for deserialization. The [string] type is intended here for serialization only, the encoding is not human-readable and may not be printable. Note that the serialization format may differ across OCaml versions. @since 5.1 *) val of_binary_string : string -> t (** Deserializes a byte sequence obtained by calling {!to_binary_string}. The resulting PRNG state will produce the same random numbers as the state that was passed as input to {!to_binary_string}. @raise Failure if the input is not in the expected format. Note that the serialization format may differ across OCaml versions. Unlike the functions provided by the {!Marshal} module, this function either produces a valid state or fails cleanly with a [Failure] exception. It can be safely used on user-provided, untrusted inputs. @since 5.1 *) end val get_state : unit -> State.t (** [get_state()] returns a fresh copy of the current state of the domain-local generator (which is used by the basic functions). *) val set_state : State.t -> unit (** [set_state s] updates the current state of the domain-local generator (which is used by the basic functions) by copying the state [s] into it. *) val split : unit -> State.t (** Draw a fresh PRNG state from the current state of the domain-local generator used by the default functions. (The state of the domain-local generator is modified.) See {!Random5.State.split}. @since 5.0 *) stdlib-random-1.2.0/random5o/000077500000000000000000000000001460153135100157745ustar00rootroot00000000000000stdlib-random-1.2.0/random5o/dune000066400000000000000000000002201460153135100166440ustar00rootroot00000000000000(library (public_name stdlib-random.v5o) (name random5o) (preprocess (action(run %{bin:cppo} -V OCAML:%{ocaml_version} %{input-file})) ) ) stdlib-random-1.2.0/random5o/prng.ml000066400000000000000000000044141460153135100172770ustar00rootroot00000000000000(**************************************************************************) (* *) (* OCaml *) (* *) (* Florian Angeletti, projet Cambium, Inria *) (* *) (* Copyright 2022 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) let m = 0xd1342543de82ef95L type state = (Int64.t, Bigarray.int64_elt, Bigarray.c_layout) Bigarray.Array1.t module Indices : sig type t = private int val a : t val s : t val x0 : t val x1 : t val (.!{}) : state -> t -> Int64.t val (.!{}<-) : state -> t -> Int64.t -> unit end = struct type t = int let a = 0 let s = 1 let x0 = 2 let x1 = 3 let (.!{}) = Bigarray.Array1.unsafe_get let (.!{}<-) = Bigarray.Array1.unsafe_set end open Indices open struct let ( + ) = Int64.add let ( * ) = Int64.mul let ( lxor ) = Int64.logxor let ( lsl ) = Int64.shift_left let ( lsr ) = Int64.shift_right_logical let ( lor ) = Int64.logor end let[@inline always] rotl x k = x lsl k lor x lsr (64-k) let next st = (* Combining operation *) let z = st.!{s} + st.!{x0} in (* Mixing function *) let z = (z lxor (z lsr 32)) * 0xdaba0b6eb09322e3L in let z = (z lxor (z lsr 32)) * 0xdaba0b6eb09322e3L in let z = (z lxor (z lsr 32)) in (* LGC update *) st.!{s} <- st.!{s} * m + st.!{a}; (* XBG update *) let q0 = st.!{x0} and q1 = st.!{x1} in let q1 = q0 lxor q1 in let q0 = rotl q0 24 in let q0 = q0 lxor q1 lxor (q1 lsl 16) in let q1 = rotl q1 37 in st.!{x0} <- q0; st.!{x1} <- q1; z stdlib-random-1.2.0/random5o/prng.mli000066400000000000000000000022421460153135100174450ustar00rootroot00000000000000(**************************************************************************) (* *) (* OCaml *) (* *) (* Florian Angeletti, projet Cambium, Inria *) (* *) (* Copyright 2022 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) type state = (Int64.t, Bigarray.int64_elt, Bigarray.c_layout) Bigarray.Array1.t val next: state -> Int64.t stdlib-random-1.2.0/random5o/random5o.ml000066400000000000000000000411371460153135100200600ustar00rootroot00000000000000(**************************************************************************) (* *) (* OCaml *) (* *) (* Damien Doligez, projet Para, INRIA Rocquencourt *) (* Xavier Leroy, projet Cambium, College de France and Inria *) (* *) (* Copyright 1996 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (* Pseudo-random number generator *) external random_seed: unit -> int array = "caml_sys_random_seed" module State = struct open Bigarray type t = (int64, int64_elt, c_layout) Array1.t let next = Prng.next let create () : t = Array1.create Int64 C_layout 4 let set s i1 i2 i3 i4 = Array1.unsafe_set s 0 (Int64.logor i1 1L); (* must be odd *) Array1.unsafe_set s 1 i2; Array1.unsafe_set s 2 (if i3 <> 0L then i3 else 1L); (* must not be 0 *) Array1.unsafe_set s 3 (if i4 <> 0L then i4 else 2L) (* must not be 0 *) let mk i1 i2 i3 i4 = let s = create () in set s i1 i2 i3 i4; s let serialization_prefix = "lxm1:" (* "lxm" denotes the algorithm currently in use, and '1' is a version number. We should update this prefix if we change the Random algorithm or the serialization format, so that users get a clean error instead of believing that they faithfully reproduce their previous state and in fact get a different stream. Note that there is no constraint to keep the same ":" format or message size in future versions, we could change the format completely if we wanted as long as there is no confusion possible with the previous formats. *) let serialization_prefix_len = String.length serialization_prefix let to_binary_string s = let prefix = serialization_prefix in let preflen = serialization_prefix_len in let buf = Bytes.create (preflen + 4 * 8) in Bytes.blit_string prefix 0 buf 0 preflen; for i = 0 to 3 do Bytes.set_int64_le buf (preflen + i * 8) (Array1.get s i) done; Bytes.unsafe_to_string buf (* Compatibility functions Imported from standard library *) #if OCAML_VERSION < (4,8,0) let set_int64_le b off n = let n = ref n in for i = 0 to 7 do Bytes.set b (off+i) Int64.(Char.unsafe_chr @@ Int64.to_int @@ logand !n 0xFFL); n := Int64.(shift_right !n 8) done #else let set_int64_le = Bytes.set_int64_le #endif #if OCAML_VERSION < (4,13,0) let get_int64_le s off = let res = ref Int64.zero in for i = 7 downto 0 do let v = Int64.of_int (Char.code s.[off+i]) in res := Int64.(add v (shift_left !res 8)) done; !res let starts_with ~prefix s = let open String in let len_s = length s and len_pre = length prefix in let rec aux i = if i = len_pre then true else if unsafe_get s i <> unsafe_get prefix i then false else aux (i + 1) in len_s >= len_pre && aux 0 #else let get_int64_le = String.get_int64_le let starts_with = String.starts_with #endif let of_binary_string buf = let prefix = serialization_prefix in let preflen = serialization_prefix_len in if String.length buf <> preflen + 4 * 8 || not (starts_with ~prefix buf) then failwith ("Random.State.of_binary_string: expected a format \ compatible with OCaml " ^ Sys.ocaml_version); let i1 = get_int64_le buf (preflen + 0 * 8) in let i2 = get_int64_le buf (preflen + 1 * 8) in let i3 = get_int64_le buf (preflen + 2 * 8) in let i4 = get_int64_le buf (preflen + 3 * 8) in mk i1 i2 i3 i4 let assign (dst: t) (src: t) = Array1.blit src dst let copy s = let s' = create() in assign s' s; s' (* The seed is an array of integers. It can be just one integer, but it can also be 12 or more bytes. To hide the difference, we serialize the array as a sequence of bytes, then hash the sequence with MD5 (Digest.bytes). MD5 gives only 128 bits while we need 256 bits, so we hash twice with different suffixes. *) let reinit s seed = let n = Array.length seed in let b = Bytes.create (n * 8 + 1) in for i = 0 to n-1 do set_int64_le b (i * 8) (Int64.of_int seed.(i)) done; Bytes.set b (n * 8) '\x01'; let d1 = Digest.bytes b in Bytes.set b (n * 8) '\x02'; let d2 = Digest.bytes b in set s (get_int64_le d1 0) (get_int64_le d1 8) (get_int64_le d2 0) (get_int64_le d2 8) let make seed = let s = create() in reinit s seed; s let make_self_init () = make (random_seed ()) let min_int31 = -0x4000_0000 (* = -2{^30}, which is [min_int] for 31-bit integers *) let max_int31 = 0x3FFF_FFFF (* = 2{^30}-1, which is [max_int] for 31-bit integers *) (* avoid integer literals for these, 32-bit OCaml would reject them: *) let min_int32 = -(1 lsl 31) (* = -0x8000_0000 on platforms where [Sys.int_size >= 32] *) let max_int32 = (1 lsl 31) - 1 (* = 0x7FFF_FFFF on platforms where [Sys.int_size >= 32] *) (* Return 30 random bits as an integer 0 <= x < 2^30 *) let bits s = Int64.to_int (next s) land max_int31 (* Return an integer between 0 (included) and [n] (excluded). [bound] may be any positive [int]. [mask] must be of the form [2{^i}-1] and greater or equal to [n]. Larger values of [mask] make the function run faster (fewer samples are rejected). Smaller values of [mask] are usable on a wider range of OCaml implementations. *) let rec int_aux s n mask = (* We start by drawing a non-negative integer in the [ [0, mask] ] range *) let r = Int64.to_int (next s) land mask in let v = r mod n in (* For uniform distribution of the result between 0 included and [n] * excluded, the random number [r] must have been drawn uniformly in * an interval whose length is a multiple of [n]. To achieve this, * we use rejection sampling on the greatest interval [ [0, k*n-1] ] * that fits in [ [0, mask] ]. That is, we reject the * sample if it falls outside of this interval, and draw again. * This is what the test below does, while carefully avoiding * overflows and sparing a division [mask / n]. *) if r - v > mask - n + 1 then int_aux s n mask else v (* Return an integer between 0 (included) and [bound] (excluded). The bound must fit in 31-bit signed integers. This function yields the same output regardless of the integer size. *) let int s bound = if bound > max_int31 || bound <= 0 then invalid_arg "Random.int" else int_aux s bound max_int31 let full_int s bound = if bound <= 0 then invalid_arg "Random.full_int" (* When the bound fits in 31-bit signed integers, we use the same mask as in function [int] so as to yield the same output on all platforms supported by OCaml (32-bit OCaml, 64-bit OCaml, and JavaScript). When the bound fits in 32-bit signed integers, we use [max_int32] as the mask so as to yield the same output on all platforms where [Sys.int_size >= 32] (i.e. JavaScript and 64-bit OCaml). *) else int_aux s bound (if bound <= max_int31 then max_int31 else if bound <= max_int32 then max_int32 else max_int) (* Return an integer between [min] (included) and [max] (included). The [nbits] parameter is the size in bits of the signed integers we draw from [s]. We must have [-2{^nbits - 1} <= min <= max < 2{^nbits - 1}]. Moreover, for the iteration to converge quickly, the interval [[min, max]] should have width at least [2{^nbits - 1}]. As the width approaches this lower limit, the average number of draws approaches 2, with a quite high standard deviation (2 + epsilon). *) let rec int_in_large_range s ~min ~max ~nbits = let drop = Sys.int_size - nbits in (* The bitshifts replicate the [nbits]-th bit (sign bit) to higher bits: *) let r = ((Int64.to_int (next s)) lsl drop) asr drop in if r < min || r > max then int_in_large_range s ~min ~max ~nbits else r (* Return an integer between [min] (included) and [max] (included). [mask] is as described for [int_aux]. [nbits] is as described for [int_in_large_range]. *) let int_in_range_aux s ~min ~max ~mask ~nbits = let span = max - min + 1 in if span <= mask (* [span] is small enough *) && span > 0 (* no overflow occurred when computing [span] *) then (* Just draw a number in [[0, span)] and shift it by [min]. *) min + int_aux s span mask else (* Span too large, use the alternative drawing method. *) int_in_large_range s ~min ~max ~nbits (* Return an integer between [min] (included) and [max] (included). We must have [min <= max]. *) let int_in_range s ~min ~max = if min > max then invalid_arg "Random.int_in_range"; (* When both bounds fit in 31-bit signed integers, we use parameters [mask] and [nbits] appropriate for 31-bit integers, so as to yield the same output on all platforms supported by OCaml. When both bounds fit in 32-bit signed integers, we use parameters [mask] and [nbits] appropriate for 32-bit integers, so as to yield the same output on JavaScript and on 64-bit OCaml. *) if min >= min_int31 && max <= max_int31 then int_in_range_aux s ~min ~max ~mask:max_int31 ~nbits:31 else if min >= min_int32 && max <= max_int32 then int_in_range_aux s ~min ~max ~mask:max_int32 ~nbits:32 else int_in_range_aux s ~min ~max ~mask:max_int ~nbits:Sys.int_size (* Return 32 random bits as an [int32] *) let bits32 s = Int64.to_int32 (next s) (* Return an [int32] between 0 (included) and [bound] (excluded). *) let rec int32aux s n = let r = Int32.shift_right_logical (bits32 s) 1 in let v = Int32.rem r n in (* Explanation of this test: see comment in [int_aux]. *) if Int32.(sub r v > add (sub max_int n) 1l) then int32aux s n else v let int32 s bound = if bound <= 0l then invalid_arg "Random.int32" else int32aux s bound (* Return an [int32] between [min] (included) and [max] (included). We must have [min <= max]. *) let rec int32_in_range_aux s ~min ~max = let r = Int64.to_int32 (next s) in if r < min || r > max then int32_in_range_aux s ~min ~max else r let int32_in_range s ~min ~max = if min > max then invalid_arg "Random.int32_in_range" else let span = Int32.succ (Int32.sub max min) in (* Explanation of this test: see comment in [int_in_range_aux]. *) if span <= Int32.zero then int32_in_range_aux s ~min ~max else Int32.add min (int32aux s span) (* Return 64 random bits as an [int64] *) let bits64 s = next s (* Return an [int64] between 0 (included) and [bound] (excluded). *) let rec int64aux s n = let r = Int64.shift_right_logical (bits64 s) 1 in let v = Int64.rem r n in (* Explanation of this test: see comment in [int_aux]. *) if Int64.(sub r v > add (sub max_int n) 1L) then int64aux s n else v let int64 s bound = if bound <= 0L then invalid_arg "Random.int64" else int64aux s bound (* Return an [int64] between [min] (included) and [max] (included). We must have [min <= max]. *) let rec int64_in_range_aux s ~min ~max = let r = next s in if r < min || r > max then int64_in_range_aux s ~min ~max else r let int64_in_range s ~min ~max = if min > max then invalid_arg "Random.int64_in_range" else let span = Int64.succ (Int64.sub max min) in (* Explanation of this test: see comment in [int_in_range_aux]. *) if span <= Int64.zero then int64_in_range_aux s ~min ~max else Int64.add min (int64aux s span) (* Return 32 or 64 random bits as a [nativeint] *) let nativebits = if Nativeint.size = 32 then fun s -> Nativeint.of_int32 (bits32 s) else fun s -> Int64.to_nativeint (bits64 s) (* Return a [nativeint] between 0 (included) and [bound] (excluded). *) let nativeint = if Nativeint.size = 32 then fun s bound -> Nativeint.of_int32 (int32 s (Nativeint.to_int32 bound)) else fun s bound -> Int64.to_nativeint (int64 s (Int64.of_nativeint bound)) (* Return a [nativeint] between [min] (included) and [max] (included). *) let nativeint_in_range = if Nativeint.size = 32 then fun s ~min ~max -> Nativeint.of_int32 (int32_in_range s ~min:(Nativeint.to_int32 min) ~max:(Nativeint.to_int32 max)) else fun s ~min ~max -> Int64.to_nativeint (int64_in_range s ~min:(Int64.of_nativeint min) ~max:(Int64.of_nativeint max)) (* Return a float 0 < x < 1 uniformly distributed among the multiples of 2^-53 *) let rec rawfloat s = let b = next s in let n = Int64.shift_right_logical b 11 in if n <> 0L then Int64.to_float n *. 0x1.p-53 else rawfloat s (* Return a float between 0 and [bound] *) let float s bound = rawfloat s *. bound (* Return a random Boolean *) let bool s = next s < 0L (* Split a new PRNG off the given PRNG *) let split s = let i1 = bits64 s in let i2 = bits64 s in let i3 = bits64 s in let i4 = bits64 s in mk i1 i2 i3 i4 end let mk_default () = (* This is the state obtained with [State.make [| 314159265 |]]. *) State.mk (-6196874289567705097L) 586573249833713189L (-8591268803865043407L) 6388613595849772044L #if OCAML_VERSION < (5,0,0) let random_key = mk_default () let bits () = State.bits random_key let int bound = State.int random_key bound let int_in_range ~min ~max = State.int_in_range random_key ~min ~max let full_int bound = State.full_int random_key bound let int32 bound = State.int32 random_key bound let int32_in_range ~min ~max = State.int32_in_range random_key ~min ~max let nativeint bound = State.nativeint random_key bound let nativeint_in_range ~min ~max = State.nativeint_in_range random_key ~min ~max let int64 bound = State.int64 random_key bound let int64_in_range ~min ~max = State.int64_in_range random_key ~min ~max let float scale = State.float random_key scale let bool () = State.bool random_key let bits32 () = State.bits32 random_key let bits64 () = State.bits64 random_key let nativebits () = State.nativebits random_key let full_init seed = State.reinit random_key seed let init seed = full_init [| seed |] let self_init () = full_init (random_seed()) (* Splitting *) let split () = State.split random_key (* Manipulating the current state. *) let get_state () = State.copy random_key let set_state s = State.assign random_key s #else let random_key = Domain.DLS.new_key ~split_from_parent:State.split mk_default let bits () = State.bits (Domain.DLS.get random_key) let int bound = State.int (Domain.DLS.get random_key) bound let full_int bound = State.full_int (Domain.DLS.get random_key) bound let int_in_range ~min ~max = State.int_in_range (Domain.DLS.get random_key) ~min ~max let int32 bound = State.int32 (Domain.DLS.get random_key) bound let int32_in_range ~min ~max = State.int32_in_range (Domain.DLS.get random_key) ~min ~max let nativeint bound = State.nativeint (Domain.DLS.get random_key) bound let nativeint_in_range ~min ~max = State.nativeint_in_range (Domain.DLS.get random_key) ~min ~max let int64 bound = State.int64 (Domain.DLS.get random_key) bound let int64_in_range ~min ~max = State.int64_in_range (Domain.DLS.get random_key) ~min ~max let float scale = State.float (Domain.DLS.get random_key) scale let bool () = State.bool (Domain.DLS.get random_key) let bits32 () = State.bits32 (Domain.DLS.get random_key) let bits64 () = State.bits64 (Domain.DLS.get random_key) let nativebits () = State.nativebits (Domain.DLS.get random_key) let full_init seed = State.reinit (Domain.DLS.get random_key) seed let init seed = full_init [| seed |] let self_init () = full_init (random_seed()) (* Splitting *) let split () = State.split (Domain.DLS.get random_key) (* Manipulating the current state. *) let get_state () = State.copy (Domain.DLS.get random_key) let set_state s = State.assign (Domain.DLS.get random_key) s #endif stdlib-random-1.2.0/random5o/random5o.mli000066400000000000000000000234551460153135100202340ustar00rootroot00000000000000(**************************************************************************) (* *) (* OCaml *) (* *) (* Damien Doligez, projet Para, INRIA Rocquencourt *) (* Xavier Leroy, projet Cambium, College de France and Inria *) (* *) (* Copyright 1996 Institut National de Recherche en Informatique et *) (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) (* the GNU Lesser General Public License version 2.1, with the *) (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (** Pseudo-random number generators (PRNG). {1 Concurrency-safety with OCaml 5 } With multiple domains, each domain has its own generator that evolves independently of the generators of other domains. When a domain is created, its generator is initialized by splitting the state of the generator associated with the parent domain. In contrast, all threads within a domain share the same domain-local generator. Independent generators can be created with the {!Random5.split} function and used with the functions from the {!Random5.State} module. *) (** {1 Basic functions} *) val init : int -> unit (** Initialize the domain-local generator, using the argument as a seed. The same seed will always yield the same sequence of numbers. *) val full_init : int array -> unit (** Same as {!Random5.init} but takes more data as seed. *) val self_init : unit -> unit (** Initialize the domain-local generator with a random seed chosen in a system-dependent way. If [/dev/urandom] is available on the host machine, it is used to provide a highly random initial seed. Otherwise, a less random seed is computed from system parameters (current time, process IDs, domain-local state). *) val bits : unit -> int (** Return 30 random bits in a nonnegative integer. *) val int : int -> int (** [Random5.int bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] must be greater than 0 and less than 2{^30}. @raise Invalid_argument if [bound] <= 0 or [bound] >= 2{^30}. *) val full_int : int -> int (** [Random5.full_int bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] may be any positive integer. If [bound] is less than 2{^31}, then [Random.full_int bound] yields identical output across systems with varying [int] sizes. If [bound] is less than 2{^30}, then [Random.full_int bound] is equal to {!Random.int}[ bound]. If [bound] is at least 2{^30} (on 64-bit systems, or non-standard environments such as JavaScript), then [Random.full_int] returns a value whereas {!Random.int} raises {!Stdlib.Invalid_argument}. @raise Invalid_argument if [bound] <= 0. @since 4.13 *) val int_in_range : min:int -> max:int -> int (** [Random5.int_in_range ~min ~max] returns a random integer between [min] (inclusive) and [max] (inclusive). Both [min] and [max] are allowed to be negative; [min] must be less than or equal to [max]. If both bounds fit in 32-bit signed integers (that is, if -2{^31} <= [min] and [max] < 2{^31}), then [int_in_range] yields identical output across systems with varying [int] sizes. @raise Invalid_argument if [min > max]. @since 5.2 *) val int32 : Int32.t -> Int32.t (** [Random5.int32 bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] must be greater than 0. @raise Invalid_argument if [bound] <= 0. *) val int32_in_range : min:int32 -> max:int32 -> int32 (** [Random5.int32_in_range ~min ~max] returns a random integer between [min] (inclusive) and [max] (inclusive). Both [min] and [max] are allowed to be negative; [min] must be less than or equal to [max]. @raise Invalid_argument if [min > max]. @since 5.2 *) val nativeint : Nativeint.t -> Nativeint.t (** [Random5.nativeint bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] must be greater than 0. @raise Invalid_argument if [bound] <= 0. *) val nativeint_in_range : min:nativeint -> max:nativeint -> nativeint (** [Random5.nativeint_in_range ~min ~max] returns a random integer between [min] (inclusive) and [max] (inclusive). Both [min] and [max] are allowed to be negative; [min] must be less than or equal to [max]. @raise Invalid_argument if [min > max]. @since 5.2 *) val int64 : Int64.t -> Int64.t (** [Random5.int64 bound] returns a random integer between 0 (inclusive) and [bound] (exclusive). [bound] must be greater than 0. @raise Invalid_argument if [bound] <= 0. *) val int64_in_range : min:int64 -> max:int64 -> int64 (** [Random.int64_in_range ~min ~max] returns a random integer between [min] (inclusive) and [max] (inclusive). Both [min] and [max] are allowed to be negative; [min] must be less than or equal to [max]. @raise Invalid_argument if [min > max]. @since 5.2 *) val float : float -> float (** [Random5.float bound] returns a random floating-point number between 0 and [bound] (inclusive). If [bound] is negative, the result is negative or zero. If [bound] is 0, the result is 0. *) val bool : unit -> bool (** [Random5.bool ()] returns [true] or [false] with probability 0.5 each. *) val bits32 : unit -> Int32.t (** [Random5.bits32 ()] returns 32 random bits as an integer between {!Int32.min_int} and {!Int32.max_int}. *) val bits64 : unit -> Int64.t (** [Random5.bits64 ()] returns 64 random bits as an integer between {!Int64.min_int} and {!Int64.max_int}. @since 4.14 *) val nativebits : unit -> Nativeint.t (** [Random5.nativebits ()] returns 32 or 64 random bits (depending on the bit width of the platform) as an integer between {!Nativeint.min_int} and {!Nativeint.max_int}. @since 4.14 *) (** {1 Advanced functions} *) (** The functions from module {!State} manipulate the current state of the random generator explicitly. This allows using one or several deterministic PRNGs, even in a multi-threaded program, without interference from other parts of the program. *) module State : sig type t (** The type of PRNG states. *) val make : int array -> t (** Create a new state and initialize it with the given seed. *) val make_self_init : unit -> t (** Create a new state and initialize it with a random seed chosen in a system-dependent way. The seed is obtained as described in {!Random5.self_init}. *) val copy : t -> t (** Return a copy of the given state. *) val bits : t -> int val int : t -> int -> int val full_int : t -> int -> int val int_in_range : t -> min:int -> max:int -> int val int32 : t -> Int32.t -> Int32.t val int32_in_range : t -> min:int32 -> max:int32 -> int32 val nativeint : t -> Nativeint.t -> Nativeint.t val nativeint_in_range : t -> min:nativeint -> max:nativeint -> nativeint val int64 : t -> Int64.t -> Int64.t val int64_in_range : t -> min:int64 -> max:int64 -> int64 val float : t -> float -> float val bool : t -> bool val bits32 : t -> Int32.t val bits64 : t -> Int64.t val nativebits : t -> Nativeint.t (** These functions are the same as the basic functions, except that they use (and update) the given PRNG state instead of the default one. *) val split : t -> t (** Draw a fresh PRNG state from the given PRNG state. (The given PRNG state is modified.) The new PRNG is statistically independent from the given PRNG. Data can be drawn from both PRNGs, in any order, without risk of correlation. Both PRNGs can be split later, arbitrarily many times. @since 5.0 *) val to_binary_string : t -> string (** Serializes the PRNG state into an immutable sequence of bytes. See {!of_binary_string} for deserialization. The [string] type is intended here for serialization only, the encoding is not human-readable and may not be printable. Note that the serialization format may differ across OCaml versions. @since 5.1 *) val of_binary_string : string -> t (** Deserializes a byte sequence obtained by calling {!to_binary_string}. The resulting PRNG state will produce the same random numbers as the state that was passed as input to {!to_binary_string}. @raise Failure if the input is not in the expected format. Note that the serialization format may differ across OCaml versions. Unlike the functions provided by the {!Marshal} module, this function either produces a valid state or fails cleanly with a [Failure] exception. It can be safely used on user-provided, untrusted inputs. @since 5.1 *) end val get_state : unit -> State.t (** [get_state()] returns a fresh copy of the current state of the domain-local generator (which is used by the basic functions). *) val set_state : State.t -> unit (** [set_state s] updates the current state of the domain-local generator (which is used by the basic functions) by copying the state [s] into it. *) val split : unit -> State.t (** Draw a fresh PRNG state from the current state of the domain-local generator used by the default functions. (The state of the domain-local generator is modified.) See {!Random5.State.split}. @since 5.0 *) stdlib-random-1.2.0/stdlib-random.opam000066400000000000000000000024251460153135100176700ustar00rootroot00000000000000# This file is generated by dune, edit dune-project instead opam-version: "2.0" version: "1.2.0" synopsis: "Versioned Random module from the OCaml standard library" description: """ The stdlib-random package provides a stable and compiler-independent implementation of all the PRNGs used in the Random module. Those PRNGs are available in the various libraries: - stdlib-random.v3: OCaml 3.07 to 3.11 PRNG - stdlib-random.v4: OCaml 3.12 to 4.14 PRNG - stdlib-random.v5: current OCaml 5.0 PRNG - stdlib-random.v5o: pure OCaml version of the OCaml 5 PRNG All those libraries can be used together and the signature of their Random$n module has been extended to the latest signature whenever possible. """ maintainer: ["Florian Angeletti, "] authors: ["Damien Doligez" "Xavier Leroy"] license: "LGPL-2.1-or-later WITH OCaml-LGPL-linking-exception" homepage: "https://github.com/ocaml/stdlib-random" bug-reports: "https://github.com/ocaml/stdlib-random/issues" depends: [ "dune" {>= "2.7"} "cppo" {>= "1.1.0"} "ocaml" {>= "4.08.0"} "odoc" {with-doc} ] build: [ ["dune" "subst"] {dev} [ "dune" "build" "-p" name "-j" jobs "@install" "@runtest" {with-test} "@doc" {with-doc} ] ] dev-repo: "git+https://github.com/ocaml/stdlib-random.git" stdlib-random-1.2.0/tests/000077500000000000000000000000001460153135100154125ustar00rootroot00000000000000stdlib-random-1.2.0/tests/binary_string_roundtrip.ml000066400000000000000000000012701460153135100227240ustar00rootroot00000000000000module type state = sig type t val to_binary_string : t -> string val of_binary_string : string -> t end module type random = sig module State: state val init: int -> unit val get_state: unit -> State.t end let test name (module R: random) = let init n = R.init n; R.get_state () in let roundtrip seed = let s = init seed in s = R.State.(of_binary_string @@ to_binary_string s) in if not @@ List.for_all roundtrip (List.init 100 Fun.id) then failwith (Format.asprintf "Roundtrip failed for %s generator" name) let () = test "random3" (module Random3); test "random4" (module Random4); test "random5" (module Random5); test "random5o" (module Random5o) stdlib-random-1.2.0/tests/binary_string_stability.ml000066400000000000000000000132501460153135100227030ustar00rootroot00000000000000module Bseed = struct let random5 = "lxm1:\239w\2416\219\017\139\172\171p\201\164\255\230}3\157\n\004f_\130\157\187\210\128\129\244!%\233T" let random4 = "lfsr2:\147\178\146\004MXF$\001\236'\017\161\t\239&F\177\195\024\144W\127\016\203\149r4oR\133\011|K\146\011)\192\1963\209\021\178-\202`\194\b\224\186\137\024\246\228e'6,,2\244\150v9T\233\224:\205\182}\007.V\168\017\176t\210\018\025`o,\1998H?\188\136\243\017xJP\bn*\207$Q\177\184(U\186}9 \206k\015\222\185>)\194\197\149-\186[\2153\138%=2\025\218\231-Z\133\244'\202\132\248)\170+\235$\149\147\217.!$\185\031\200\162\137#of\135:U\180}\024\234u[$=\234\179\007\019r\156&\255\162\252\027\0219b5\152\198\2546\222R\158\t\205%\210\020\213\207\252\011\219P\011)'\143\206+\151V\244\005\165\145\"+\031\169\139\020\000" let random3 = "lfsr1:\147\178\1461MXF9\001\236g\020\161\to\025F\177\195\022\144W\127\020\203\149r\roRE\"|KR\018)\192\004\028\209\021\242+\202`\194\002\224\186\137&\246\228\16596,\172\028\244\1506\030T\233`>\205\182\189!.V\2324\176tR$\025`o\027\1998\136?\188\136\179\004xJP\018n*\2079Q\177\184\nU\186=. \206\171\003\222\185~:\194\197\213\011\186[\023<\138%\189\012\025\218\167\011Z\1334\025\202\132\184*\170+\235\025\149\147Y\027!$y\023\200\162I\024of\007\014U\180}\022\234u[)=\234s\017\019r\0289\255\162<&\0219\"=\152\198~=\222R\222\002\205%\210\021\213\207<2\219PK:'\143\014*\151V\180!\165\145\226\n\031\169\139\005\000" end module Ref = struct let random5 = [51205518; 143567504; 373210087; 931777272; 1024888384; 482316132; 215395062; 287774887; 122637722; 38242823; 350835997; 630681959; 718778024; 1065436210; 43244835; 609003301; 259142195; 1039388409; 905127179; 164615882; 221116766; 383401359; 788855748; 722758384; 662498126; 495247601; 671365454; 719912258; 474192479; 734524651; 577331096; 1019075908; 545637817; 578658943; 980379849; 457833426; 808752211; 1027037899; 384530842; 586472994; 779070294; 504262909; 839642021; 569868070; 653106634; 462343329; 195606612; 400414219; 437410999; 1065973528; 184562054; 8977365; 701766686; 1030788046; 201158226; 993355978; 513186390; 793044777; 266183426; 748055767; 106963046; 264533467; 468538478; 914245566; 530582367; 967537841; 998977830; 845571161; 555948857; 1005737806; 106600589; 262202732; 675506221; 116323840; 529666627; 137258302; 696020801; 237746569; 109239396; 85391287; 662583924; 1035066826; 170367049; 48279585; 434780163; 686477977; 637582722; 537604125; 339045636; 673659184; 443413333; 773842082; 430598577; 531224810; 63845424; 720907323; 1042853427; 730867490; 834910774; 749645142] let random4 = [218040752; 178628190; 911923154; 33712936; 1041571162; 675934603; 1036154868; 964306322; 465126794; 397056657; 766348408; 123948673; 119474438; 364236535; 872283479; 324967838; 735653048; 425476195; 963569356; 141296398; 883585517; 150097740; 300850522; 966873161; 884310298; 579406628; 993680718; 791875681; 414734201; 140707010; 919590950; 988210111; 848964519; 542334128; 653104864; 753840348; 134419897; 558635725; 872516612; 876018147; 1007030409; 895579830; 771735681; 589016056; 186124294; 721208282; 486338680; 11227775; 626593843; 578434971; 876253760; 983484546; 873783548; 645547631; 1043595994; 28609232; 758034815; 831862039; 825588618; 382563518; 816641633; 882003984; 878774605; 240349486; 939390794; 345711438; 877789022; 253894334; 922872266; 671058258; 127244154; 668941622; 247314213; 661563217; 730312450; 1069709821; 871306018; 787189194; 978100948; 437162291; 84099792; 796192659; 701618424; 214775921; 786254645; 889445143; 1016819314; 533257533; 300454327; 404951677; 62662024; 951061534; 366897901; 677549419; 42625831; 872679393; 167549434; 575782901; 842910375; 35254733] let random3 = [67045790; 44410454; 488298433; 289565476; 542448978; 160035205; 788690937; 502932885; 892945795; 380279451; 481135732; 31673973; 287246615; 888524542; 742260067; 350133673; 186199223; 106709099; 493807299; 28050200; 1017803228; 36851540; 355376470; 262230075; 1022722342; 680069936; 767188295; 473108597; 381179751; 27460825; 1045420061; 262595511; 467282864; 131292299; 724408014; 1001304295; 553850278; 122428097; 738298884; 196540888; 397445; 773945009; 989839496; 928754710; 840435731; 700236795; 398258311; 552292996; 949555264; 398079902; 733647423; 509528179; 219472121; 448415349; 20185806; 16026308; 724480390; 181744904; 762674073; 923628729; 187496030; 760369174; 765528396; 286486835; 511571750; 131801922; 1032978268; 841096893; 1010952639; 406817127; 546674561; 186596668; 880654108; 409904971; 956804910; 784497135; 737088335; 753634781; 814523071; 898535782; 4408014; 427093894; 982636776; 600651872; 475876174; 1065605867; 278621819; 118021430; 313037203; 413340263; 851191200; 741346308; 882797271; 430085456; 483027723; 511969195; 905746931; 949075940; 696109779; 777646546] end let gen bits = List.init 100 (fun _ -> bits ()) let failure reader seed = try ignore (reader seed); false with Failure _ -> true let () = let () = Random3.(set_state @@ State.of_binary_string @@ Bseed.random3) in let () = Random4.(set_state @@ State.of_binary_string @@ Bseed.random4) in let () = Random5.(set_state @@ State.of_binary_string @@ Bseed.random5) in let () = Random5o.(set_state @@ State.of_binary_string @@ Bseed.random5) in assert (gen Random3.bits = Ref.random3); assert (gen Random4.bits = Ref.random4); assert (gen Random5.bits = Ref.random5); assert (gen Random5o.bits = Ref.random5); assert(failure Random5.State.of_binary_string Bseed.random4); assert(failure Random4.State.of_binary_string Bseed.random5); assert(failure Random3.State.of_binary_string Bseed.random4) stdlib-random-1.2.0/tests/chi2.ml000066400000000000000000000322601460153135100165740ustar00rootroot00000000000000(* Imported from OCaml testsuite to test feature backports *) module Test(Name:sig val name:string end)(Random:module type of Random3) = struct let chisquare n f = let r = 256 in let freq = Array.make r 0 in for _i = 0 to n - 1 do let t = f () land 0xFF in freq.(t) <- freq.(t) + 1 done; let expected = float n /. float r in let t = Array.fold_left (fun s x -> let d = float x -. expected in d *. d +. s) 0.0 freq in let chi2 = t /. expected in let degfree = float r -. 1.0 in (* The degree of freedom is high, so we approximate as a normal distribution with mean equal to degfree and variance 2 * degfree. Four sigmas correspond to a 99.9968% confidence interval. (Without the approximation, the confidence interval seems to be 99.986%.) *) chi2 <= degfree +. 4.0 *. sqrt (2.0 *. degfree) let test name f = if not (chisquare 100_000 f) then Printf.printf "%s,%s: suspicious result\n%!" Name.name name (* Division of [x] by [y] where [x] is interpreted as an unsigned integer. * This code assumes [y >= 0]. *) let udiv x y = if x >= 0 then x / y else let x' = x + min_int in let q = (x' / y) - (min_int / y) and r = (x' mod y) - (min_int mod y) in if r < y then q else q + 1 let _ = (* [bits] *) test "Random.bits (bits 0-7)" Random.bits; test "Random.bits (bits 12-19)" (fun () -> Random.bits() lsr 12); test "Random.bits (bits 22-29)" (fun () -> Random.bits() lsr 22); (* [int] *) test "Random.int 2^26 (bits 0-7)" (fun () -> Random.int (1 lsl 26)); test "Random.int 2^26 (bits 18-25)" (fun () -> Random.int (1 lsl 26) lsr 18); test "Random.int (256 * p) / p" (fun () -> Random.int (256 * 853187) / 853187); (* [float] *) test "Random.float 1.0 (first 8 bits)" (fun () -> int_of_float (Random.float 1.0 *. 256.0)); test "Random.float 1.0 (next 8 bits)" (fun () -> int_of_float (Random.float 1.0 *. 65536.0)); (* [bits32] *) test "Random.bits32 (bits 0-7)" (fun () -> Int32.to_int (Random.bits32())); test "Random.bits32 (bits 20-27)" (fun () -> Int32.(to_int (shift_right (Random.bits32()) 20))); (* [int32] *) test "Random.int32 2^30 (bits 0-7)" (fun () -> Int32.to_int (Random.int32 0x40000000l)); test "Random.int32 2^30 (bits 20-27)" (fun () -> Int32.(to_int (shift_right (Random.int32 0x40000000l) 20))); test "Random.int32 (256 * p) / p" (let p = 7048673l in fun () -> Int32.(to_int (div (Random.int32 (mul 256l p)) p))); (* [bits64] *) test "Random.bits64 (bits 0-7)" (fun () -> Int64.to_int (Random.bits64())); test "Random.bits64 (bits 30-37)" (fun () -> Int64.(to_int (shift_right (Random.bits64()) 30))); test "Random.bits64 (bits 52-59)" (fun () -> Int64.(to_int (shift_right (Random.bits64()) 52))); (* [int64] *) test "Random.int64 2^60 (bits 0-7)" (fun () -> Int64.to_int (Random.int64 0x1000000000000000L)); test "Random.int64 2^60 (bits 30-37)" (fun () -> Int64.(to_int (shift_right (Random.int64 0x1000000000000000L) 30))); test "Random.int64 2^60 (bits 52-59)" (fun () -> Int64.(to_int (shift_right (Random.int64 0x1000000000000000L) 52))); test "Random.int64 (256 * p) / p" (let p = 16430454264262693L in fun () -> Int64.(to_int (div (Random.int64 (mul 256L p)) p))); (* [full_int] *) if Sys.int_size >= 32 then begin test "Random.full_int 2^30 (bits 0-7)" (fun () -> Random.full_int (1 lsl 30)); test "Random.full_int 2^30 (bits 22-29)" (fun () -> Random.full_int (1 lsl 30) lsr 22); test "Random.full_int (256 * p) / p" (let p = 7992689 in fun () -> Random.full_int (256 * p) / p) end; if Sys.int_size >= 63 then begin test "Random.full_int 2^60 (bits 0-7)" (fun () -> Random.full_int (1 lsl 60)); test "Random.full_int 2^60 (bits 30-37)" (fun () -> Random.full_int (1 lsl 60) lsr 30); test "Random.full_int 2^60 (bits 52-59)" (fun () -> Random.full_int (1 lsl 60) lsr 52); test "Random.full_int (256 * P) / P" (let p = Int64.to_int 17766642568158577L in fun () -> Random.full_int (256 * p) / p) end; (* [int_in_range] *) let min_ = -214748364 in let max_ = min_ + 0x1FFF_FFFF in test "Random.int_in_range, range of length 2^29 (bits 0-7)" (fun () -> Random.int_in_range ~min:min_ ~max:max_ - min_); test "Random.int_in_range, range of length 2^29 (bits 21-28)" (fun () -> (Random.int_in_range ~min:min_ ~max:max_ - min_) lsr 21); let min_ = -214748364 in let max_ = min_ + 0x3FFF_FFFF in test "Random.int_in_range, range of length 2^30 (bits 0-7)" (fun () -> Random.int_in_range ~min:min_ ~max:max_ - min_); test "Random.int_in_range, range of length 2^30 (bits 22-29)" (fun () -> (Random.int_in_range ~min:min_ ~max:max_ - min_) lsr 22); let min_int31 = -0x4000_0000 in let max_int31 = 0x3FFF_FFFF in test "Random.int_in_range, full int31 range (bits 0-7)" (fun () -> Random.int_in_range ~min:min_int31 ~max:max_int31); test "Random.int_in_range, full int31 range (bits 23-30)" (fun () -> (Random.int_in_range ~min:min_int31 ~max:max_int31) lsr 23); test "Random.int_in_range, range of length 256*p < 2^30 (bits 0-7)" (let p = 2_097_169 in (* prime < 2^22 *) let min_ = -214748364 in let max_ = min_ + (256 * p) - 1 in fun () -> (Random.int_in_range ~min:min_ ~max:max_ - min_) / p); test "Random.int_in_range, range of length 2^30 < 256*p < 2^31 (bits 0-7)" (let p = 6_291_469 in (* prime > 2^22 and < 2^23 *) let min_ = min_int in let max_ = min_ + (256 * p) - 1 in fun () -> udiv (Random.int_in_range ~min:min_ ~max:max_ - min_) p); if Sys.int_size >= 32 then begin let min_int32 = Int64.to_int (-0x8000_0000L) in let max_int32 = Int64.to_int 0x7FFF_FFFFL in test "Random.int_in_range, full int32 range (bits 0-7)" (fun () -> Random.int_in_range ~min:min_int32 ~max:max_int32); test "Random.int_in_range, full int32 range (bits 24-31)" (fun () -> (Random.int_in_range ~min:min_int32 ~max:max_int32) lsr 24); test "Random.int_in_range, range of length 2^31 < 256*p < 2^32 (bits 0-7)" (let p = 12_582_917 in (* prime > 2^23 and < 2^24 *) let min_ = min_int in let max_ = min_ + (256 * p) - 1 in fun () -> udiv (Random.int_in_range ~min:min_ ~max:max_ - min_) p); end; if Sys.int_size >= 63 then begin let min_ = Int64.to_int (-1844674407370955197L) in let max_ = min_ + Int64.to_int 0x1FFF_FFFF_FFFF_FFFFL in test "Random.int_in_range, range of length 2^61 (bits 0-7)" (fun () -> Random.int_in_range ~min:min_ ~max:max_ - min_); test "Random.int_in_range, range of length 2^61 (bits 30-37)" (fun () -> (Random.int_in_range ~min:min_ ~max:max_ - min_) lsr 30); test "Random.int_in_range, range of length 2^61 (bits 53-60)" (fun () -> (Random.int_in_range ~min:min_ ~max:max_ - min_) lsr 53); let min_ = Int64.to_int (-1844674407370955197L) in let max_ = min_ + Int64.to_int 0x3FFF_FFFF_FFFF_FFFFL in test "Random.int_in_range, range of length 2^62 (bits 0-7)" (fun () -> Random.int_in_range ~min:min_ ~max:max_ - min_); test "Random.int_in_range, range of length 2^62 (bits 30-37)" (fun () -> (Random.int_in_range ~min:min_ ~max:max_ - min_) lsr 30); test "Random.int_in_range, range of length 2^62 (bits 54-61)" (fun () -> (Random.int_in_range ~min:min_ ~max:max_ - min_) lsr 54); test "Random.int_in_range, full int range (bits 0-7)" (fun () -> Random.int_in_range ~min:min_int ~max:max_int); test "Random.int_in_range, full int range (bits 30-37)" (fun () -> (Random.int_in_range ~min:min_int ~max:max_int) lsr 30); test "Random.int_in_range, full int range (bits 55-62)" (fun () -> (Random.int_in_range ~min:min_int ~max:max_int) lsr 55); test "Random.int_in_range, range of length 2^61 < 256*p < 2^62 (bits 0-7)" (let p = Int64.to_int 13510798882111519L in (*prime > 2^53 and < 2^54 *) let min_ = min_int in let max_ = min_ + (256 * p) - 1 in fun () -> (Random.int_in_range ~min:min_ ~max:max_ - min_) / p); test "Random.int_in_range, range of length 256*p > 2^62 (bits 0-7)" (let p = Int64.to_int 27021597764223071L in (*prime > 2^54 and < 2^55 *) let min_ = min_int in let max_ = min_ + (256 * p) - 1 in fun () -> udiv (Random.int_in_range ~min:min_ ~max:max_ - min_) p); end; (* [int32_in_range] *) let min_ = -429496751l in let max_ = Int32.add min_ 0x3FFF_FFFFl in test "Random.int32_in_range, range of length 2^30 (bits 0-7)" (fun () -> Int32.(to_int (sub (Random.int32_in_range ~min:min_ ~max:max_) min_))); test "Random.int32_in_range, range of length 2^30 (bits 22-29)" (fun () -> Int32.(to_int (shift_right (sub (Random.int32_in_range ~min:min_ ~max:max_) min_) 22))); let min_ = -429496751l in let max_ = Int32.add min_ 0x7FFF_FFFFl in test "Random.int32_in_range, range of length 2^31 (bits 0-7)" (fun () -> Int32.(to_int (sub (Random.int32_in_range ~min:min_ ~max:max_) min_))); test "Random.int32_in_range, range of length 2^31 (bits 23-30)" (fun () -> Int32.(to_int (shift_right (sub (Random.int32_in_range ~min:min_ ~max:max_) min_) 23))); test "Random.int32_in_range, full int32 range (bits 0-7)" (fun () -> Int32.(to_int (Random.int32_in_range ~min:min_int ~max:max_int))); test "Random.int32_in_range, full int32 range (bits 24-31)" (fun () -> Int32.(to_int (shift_right (Random.int32_in_range ~min:min_int ~max:max_int) 24))); test "Random.int32_in_range, range of length 256*p < 2^31 (bits 0-7)" (let p = 6_291_469l in (* prime < 2^23 *) let min_ = -429496751l in let max_ = Int32.(pred (add min_ (mul 256l p))) in fun () -> Int32.(to_int (div (sub (Random.int32_in_range ~min:min_ ~max:max_) min_) p))); test "Random.int32_in_range, range of length 256*p > 2^31 (bits 0-7)" (let p = 12_582_917l in (* prime > 2^23 and < 2^24 *) let min_ = Int32.min_int in let max_ = Int32.(pred (add min_ (mul 256l p))) in fun () -> Int32.(to_int (unsigned_div (sub (Random.int32_in_range ~min:min_ ~max:max_) min_) p))); (* [int64_in_range] *) let min_ = -1844674407370955197L in let max_ = Int64.add min_ 0x3FFF_FFFF_FFFF_FFFFL in test "Random.int64_in_range, range of length 2^62 (bits 0-7)" (fun () -> Int64.(to_int (sub (Random.int64_in_range ~min:min_ ~max:max_) min_))); test "Random.int64_in_range, range of length 2^62 (bits 30-37)" (fun () -> Int64.(to_int (shift_right (sub (Random.int64_in_range ~min:min_ ~max:max_) min_) 30))); test "Random.int64_in_range, range of length 2^62 (bits 54-61)" (fun () -> Int64.(to_int (shift_right (sub (Random.int64_in_range ~min:min_ ~max:max_) min_) 54))); let min_ = -1844674407370955197L in let max_ = Int64.add min_ 0x7FFF_FFFF_FFFF_FFFFL in test "Random.int64_in_range, range of length 2^63 (bits 0-7)" (fun () -> Int64.(to_int (sub (Random.int64_in_range ~min:min_ ~max:max_) min_))); test "Random.int64_in_range, range of length 2^63 (bits 30-37)" (fun () -> Int64.(to_int (shift_right (sub (Random.int64_in_range ~min:min_ ~max:max_) min_) 30))); test "Random.int64_in_range, range of length 2^63 (bits 55-62)" (fun () -> Int64.(to_int (shift_right (sub (Random.int64_in_range ~min:min_ ~max:max_) min_) 55))); test "Random.int64_in_range, full int64 range (bits 0-7)" (fun () -> Int64.(to_int (Random.int64_in_range ~min:min_int ~max:max_int))); test "Random.int64_in_range, full int64 range (bits 30-37)" (fun () -> Int64.(to_int (shift_right (Random.int64_in_range ~min:min_int ~max:max_int) 30))); test "Random.int64_in_range, full int64 range (bits 56-63)" (fun () -> Int64.(to_int (shift_right (Random.int64_in_range ~min:min_int ~max:max_int) 56))); test "Random.int64_in_range, range of length 256*p < 2^63 (bits 0-7)" (let p = 27021597764223071L in (* prime < 2^55 *) let min_ = -1844674407370955197L in let max_ = Int64.(pred (add min_ (mul 256L p))) in fun () -> Int64.(to_int (div (sub (Random.int64_in_range ~min:min_ ~max:max_) min_) p))); test "Random.int64_in_range, range of length 256*p > 2^63 (bits 0-7)" (let p = 54043195528445957L in (* prime > 2^55 and < 2^56 *) let min_ = Int64.min_int in let max_ = Int64.(pred (add min_ (mul 256L p))) in fun () -> Int64.(to_int (unsigned_div (sub (Random.int64_in_range ~min:min_ ~max:max_) min_) p))); end module R3 = Test(struct let name = "Random3" end)(Random3) module R4 = Test(struct let name = "Random4" end)(Random4) module R5 = Test(struct let name = "Random5" end)(Random5) module R6 = Test(struct let name = "Random5o" end)(Random5o) stdlib-random-1.2.0/tests/consistency.ml000066400000000000000000000014321460153135100203050ustar00rootroot00000000000000(* Check that only split is missing from implementations anterior to Random5 *) module type r3 = module type of Random3 module type r4 = module type of Random4 module type r5 = module type of Random5 module type r5o = module type of Random5o module R5_to_R4(R5:r5): r4 = R5 module R4_to_R5(R4:r4): r5 = struct module State = struct include R4.State let split x = x end include (R4: r4 with module State := State) let split () = State.split (get_state ()) end module R5o_equal_R5:sig module type t = r5 end = struct module type t = r5o end module R3_equal_R4:sig module type t = r3 end = struct module type t = r4 end #if OCAML_VERSION >= (5,2,0) module R5_equal_Stdlib: sig module type t = r5 end = struct module type t = module type of Stdlib__Random end #endif stdlib-random-1.2.0/tests/dune000066400000000000000000000011271460153135100162710ustar00rootroot00000000000000(test (name random3_test) (libraries random3) (modules Random3_test) ) (test (name random4_test) (libraries random4) (modules Random4_test) ) (test (name random5_test) (libraries random5 random5o) (modules Random5_test) ) (tests (names binary_string_roundtrip binary_string_stability chi2) (modules binary_string_roundtrip binary_string_stability chi2) (libraries random3 random4 random5 random5o) ) (test (name consistency) (libraries random3 random4 random5 random5o) (preprocess (action (run %{bin:cppo} -V OCAML:%{ocaml_version} %{input-file}))) (modules Consistency) ) stdlib-random-1.2.0/tests/random3_test.ml000066400000000000000000000022741460153135100203530ustar00rootroot00000000000000let array =[|43912428; 50948593; 190204223; 1182778; 8476367; 69420907; 442520671; 415602325; 14100924; 358914778; 7706935; 182876656; 267496847; 67366534; 515049525; 328741006; 172024291; 214616330; 404924642; 523596505; 49059379; 116839578; 223328214; 376791369; 1230043; 505817095; 463055100; 196306511; 265426042; 120055538; 152713203; 510105334; 492135262; 18874896; 223743250; 139652427; 156322660; 215149727; 532746946; 152288584; 487850872; 163641345; 488235231; 88252913; 484417929; 466441459; 64447684; 458932813; 78783099; 295980017; 262662588; 346667979; 161017702; 19920265; 113460383; 45142471; 19894776; 116388411; 197489289; 273902409; 189476445; 58362962; 388836747; 506236186; 377789674; 231450185; 322529083; 423819507; 282516261; 510925559; 481029590; 123004251; 378257675; 356288961; 74978506; 533477308; 46410125; 287775898; 298853270; 80013142; 264926200; 188846776; 6103578; 426443744; 139975803; 266173586; 18376893; 512030038; 135263307; 421232539; 413554836; 345799105; 273512689; 384712781; 121653858; 328769634; 395091530; 273893402; 512072420; 230063278|] let () = assert (Random3.init 100; Array.init 100 (fun _ -> Random3.int (1 lsl 29) ) = array ) stdlib-random-1.2.0/tests/random4_test.ml000066400000000000000000000046611460153135100203560ustar00rootroot00000000000000let major = Scanf.sscanf Sys.ocaml_version "%d.%_d.%_d" (fun x -> x) let l = if major = 4 then (Random.init 100; List.init 100 (fun _ -> Random.float 1.)) else [0X1.492D3BA4AF068P-3; 0X1.290622DDAC928P-5; 0X1.023476C14055BP-2; 0X1.E85969D988151P-2; 0X1.4249AE8035CA7P-2; 0X1.7133CF7886B32P-1; 0X1.0C3EE84F9C6B6P-2; 0X1.9306141CF9842P-3; 0X1.A0564884D81C4P-1; 0X1.EFAB9633CC552P-1; 0X1.CF6D48D3BB259P-2; 0X1.935613FE03EEP-2; 0X1.B3313FFFEA58AP-1; 0X1.599B31E5FB352P-1; 0X1.B67E6ECF84852P-2; 0X1.B73CB8E45347P-1; 0X1.4800867295635P-4; 0X1.1A976A3F22C1AP-1; 0X1.889765148A297P-1; 0X1.089DEA6720225P-1; 0X1.5E07C0564A807P-1; 0X1.542A1E5DE6783P-2; 0X1.846AA6CE7BF43P-1; 0X1.56D6123A12ECAP-1; 0X1.722602A664452P-5; 0X1.3A9BBC2FC9FA7P-2; 0X1.9BFD692598EF5P-4; 0X1.161A3DED21A25P-3; 0X1.EAFF21902BE47P-2; 0X1.89B5AB5B0AE5P-5; 0X1.17518635C5972P-3; 0X1.9B646832ADA5BP-1; 0X1.EA5D31DB2893AP-1; 0X1.1617C6122F2CEP-1; 0X1.97A0D7283ADB6P-1; 0X1.914E545B6AFB8P-2; 0X1.5FC89C17F2F04P-2; 0X1.661BE2A670298P-5; 0X1.14E39866C214BP-3; 0X1.284E78210408EP-2; 0X1.780C947F294E8P-1; 0X1.1D581FA7DBA44P-1; 0X1.E6EBE43C3AFB9P-1; 0X1.9A27A937F30D2P-1; 0X1.34DBFCA479FE8P-1; 0X1.FB8F33B3332C5P-3; 0X1.CDC809FCE6BC7P-3; 0X1.73140B6A40253P-3; 0X1.22690014864F3P-3; 0X1.ADB3E5EF00B35P-1; 0X1.F21A968C702DFP-1; 0X1.97EF1CD87DF4FP-1; 0X1.25FFE73638357P-2; 0X1.98E8C51ACEBE7P-1; 0X1.E5368123C5C4AP-2; 0X1.CFD02E0366B73P-1; 0X1.6314A409B6309P-1; 0X1.AC6159535F37AP-3; 0X1.505969A166023P-2; 0X1.E8A4895CD6305P-1; 0X1.BEFDFF1C7CE4BP-1; 0X1.DD22A0CE53EE5P-1; 0X1.161C2302C4B69P-5; 0X1.1B0BEEB256C2DP-3; 0X1.67B5ECAF87E8EP-3; 0X1.882CC80710569P-1; 0X1.FFF2C3C6EA6FAP-4; 0X1.22B49BA160B2DP-2; 0X1.5531584058644P-2; 0X1.877777FAD9039P-1; 0X1.ACE22566CC393P-2; 0X1.8C0BC655A7DF6P-1; 0X1.A49901497F0AP-3; 0X1.FB2C0D9BA7F09P-1; 0X1.D98E656C6E7AEP-1; 0X1.9E7880E45698CP-3; 0X1.552868E81E61P-1; 0X1.271E58162B5A2P-1; 0X1.44E969D00DF16P-1; 0X1.BF853CA77AC86P-1; 0X1.DF15038ECED6FP-3; 0X1.6018205908AC7P-2; 0X1.05C42434CA666P-1; 0X1.E262B5C612A7DP-3; 0X1.EC345F0036B54P-1; 0X1.06476B4FCA3F4P-1; 0X1.3F07D55BF4EE4P-2; 0X1.B729CD85D2C14P-1; 0X1.FBDED9A28244P-3; 0X1.26B1916F613ABP-1; 0X1.6AD5B9FFABC0AP-1; 0X1.0016CD5AB9847P-1; 0X1.4EEC2AEEBC579P-1; 0X1.D67EABD5E9642P-4; 0X1.590E1BC273E12P-6; 0X1.EFF3EEA286FC5P-2; 0X1.D75671EC8977BP-1; 0X1.8417D21BC1C3BP-6; 0X1.CB2253FF70D4EP-1; 0X1.4B3BE1C02523AP-2] let () = assert (Random4.init 100; List.init 100 (fun _ -> Random4.float 1.) = l ) stdlib-random-1.2.0/tests/random5_test.ml000066400000000000000000000047711460153135100203610ustar00rootroot00000000000000let major = Scanf.sscanf Sys.ocaml_version "%d.%_d.%_d" (fun x -> x) let ref = if major = 5 then (Random.init 100; List.init 100 (fun _ -> Random.float 1.0)) else [0X1.34133E66775C4P-2; 0X1.9ED1065A86444P-2; 0X1.1905BA466B65DP-1; 0X1.0AB3D91AA60B6P-2; 0X1.76EF458B68A9AP-2; 0X1.3848F5D2B7A3DP-1; 0X1.D302161743C4CP-3; 0X1.84EA303D6345CP-2; 0X1.6313BC2D6AF2CP-3; 0X1.42A3123A45D3AP-2; 0X1.8E7C2E67B1E6DP-1; 0X1.DF08E2052BF6EP-2; 0X1.750FECA48ADC5P-1; 0X1.DC7F5ED6DC40EP-1; 0X1.E6604AB6ACBC6P-1; 0X1.D173F55C661AP-5; 0X1.DCDB15924AFA4P-3; 0X1.B54D85B7A3CE5P-1; 0X1.2EE1B60BECC26P-2; 0X1.9CC3A1A1BEFC8P-1; 0X1.FB1030560065P-3; 0X1.DADF8C7B45E57P-1; 0X1.9E1B05275866P-5; 0X1.E13960D211238P-1; 0X1.D774CE26356D8P-1; 0X1.4A5BE2BFBFB29P-1; 0X1.1DD3B82B5334CP-2; 0X1.3102A2772CDEEP-1; 0X1.9A3FE1483E8P-1; 0X1.C134916189P-11; 0X1.4E676AB56EE08P-4; 0X1.3673C7517ADD8P-4; 0X1.2304163AA61CP-3; 0X1.58BC3D7C281P-8; 0X1.70CBA20B0BAF4P-3; 0X1.F645F2F7A14CP-3; 0X1.93DB9AB026EDFP-1; 0X1.D33CCDC7CA6A6P-1; 0X1.C41077D716402P-1; 0X1.0794A378450A6P-2; 0X1.99135445AAB98P-2; 0X1.CEABC40108E48P-4; 0X1.7F3C8F162AE09P-1; 0X1.8D1D792161266P-2; 0X1.F7B3DA5F4D206P-2; 0X1.81699D95EA929P-1; 0X1.36DDEB5EE2AB2P-1; 0X1.345E5F7A5D29DP-1; 0X1.83258F1E80044P-1; 0X1.E264DC5F467B6P-1; 0X1.B96E76BE0DA03P-1; 0X1.B6E8344121E8CP-3; 0X1.8500E346E25A4P-1; 0X1.C96515019DA2AP-2; 0X1.D8C3575C8DA8EP-2; 0X1.43EDF731532DCP-1; 0X1.6FCDD78F8E321P-1; 0X1.B8F59DD84D91EP-2; 0X1.447FD1179BE73P-1; 0X1.E2DF8F0C1891EP-2; 0X1.CE85C7BA64CD9P-1; 0X1.0ADC116F6A22P-4; 0X1.2FC6A659EC988P-2; 0X1.B7374C6051384P-2; 0X1.E100379312AC8P-4; 0X1.554D8449441BP-1; 0X1.38D2E36EED9E9P-1; 0X1.76BC58BC77CP-8; 0X1.C1D21C5379F18P-1; 0X1.5146DB427C0A8P-4; 0X1.8F282BFA8FEECP-3; 0X1.2290C0F49CBDCP-1; 0X1.F4DD85E368D93P-1; 0X1.D06EEF6371105P-1; 0X1.68143A1E48D28P-2; 0X1.334BD10BD1696P-1; 0X1.3AC52D2DF5C78P-2; 0X1.3061EE1E6A559P-1; 0X1.9DFFEDBE41F2P-4; 0X1.DC11B951660AP-2; 0X1.1C6CF4ADCFE23P-1; 0X1.5D03E255604AP-3; 0X1.F466FE9A9ADEP-1; 0X1.A5586F9F281E6P-1; 0X1.9CDB5EC6EEA5DP-1; 0X1.5C5EA06497F2BP-1; 0X1.22AEFE5E3944FP-1; 0X1.9E8C415A90B69P-1; 0X1.DD595DEAAB05FP-1; 0X1.92739123EF9P-8; 0X1.A38A4C5EC3788P-2; 0X1.8FFCA4E97A878P-3; 0X1.995CAD9BD07CBP-1; 0X1.27A2DC80F5658P-2; 0X1.2A139A88EF364P-3; 0X1.64FDDD10C3B78P-1; 0X1.C86C3B772D186P-2; 0X1.C4E14F19D0B45P-1; 0X1.BD1F7FBF4775P-2; 0X1.2FEB1DF02846CP-1] let () = assert (Random5.init 100; List.init 100 (fun _ -> Random5.float 1.) = ref ); assert (Random5o.init 100; List.init 100 (fun _ -> Random5o.float 1.) = ref );