123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309 |
- <!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="rustdoc"><meta name="description" content="API documentation for the Rust `rand` crate."><meta name="keywords" content="rust, rustlang, rust-lang, rand"><title>rand - Rust</title><link rel="stylesheet" type="text/css" href="../normalize.css"><link rel="stylesheet" type="text/css" href="../rustdoc.css" id="mainThemeStyle"><link rel="stylesheet" type="text/css" href="../dark.css"><link rel="stylesheet" type="text/css" href="../light.css" id="themeStyle"><script src="../storage.js"></script><link rel="shortcut icon" href="https://www.rust-lang.org/favicon.ico"></head><body class="rustdoc mod"><!--[if lte IE 8]><div class="warning">This old browser is unsupported and will most likely display funky things.</div><![endif]--><nav class="sidebar"><div class="sidebar-menu">☰</div><a href='../rand/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk.png' alt='logo' width='100'></a><p class='location'>Crate rand</p><div class="sidebar-elems"><div class="block items"><ul><li><a href="#modules">Modules</a></li><li><a href="#structs">Structs</a></li><li><a href="#enums">Enums</a></li><li><a href="#traits">Traits</a></li><li><a href="#functions">Functions</a></li></ul></div><p class='location'></p><script>window.sidebarCurrent = {name: 'rand', ty: 'mod', relpath: '../'};</script></div></nav><div class="theme-picker"><button id="theme-picker" aria-label="Pick another theme!"><img src="../brush.svg" width="18" alt="Pick another theme!"></button><div id="theme-choices"></div></div><script src="../theme.js"></script><nav class="sub"><form class="search-form js-only"><div class="search-container"><input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"><a id="settings-menu" href="../settings.html"><img src="../wheel.svg" width="18" alt="Change settings"></a></div></form></nav><section id="main" class="content"><h1 class='fqn'><span class='in-band'>Crate <a class="mod" href=''>rand</a></span><span class='out-of-band'><span id='render-detail'><a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">[<span class='inner'>−</span>]</a></span><a class='srclink' href='../src/rand/lib.rs.html#11-1252' title='goto source code'>[src]</a></span></h1><div class='docblock'><p>Utilities for random number generation</p>
- <p>Rand provides utilities to generate random numbers, to convert them to
- useful types and distributions, and some randomness-related algorithms.</p>
- <h1 id="basic-usage" class="section-header"><a href="#basic-usage">Basic usage</a></h1>
- <p>To get you started quickly, the easiest and highest-level way to get
- a random value is to use <a href="fn.random.html"><code>random()</code></a>.</p>
- <pre class="rust rust-example-rendered">
- <span class="kw">let</span> <span class="ident">x</span>: <span class="ident">u8</span> <span class="op">=</span> <span class="ident">rand</span>::<span class="ident">random</span>();
- <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">x</span>);
- <span class="kw">let</span> <span class="ident">y</span> <span class="op">=</span> <span class="ident">rand</span>::<span class="ident">random</span>::<span class="op"><</span><span class="ident">f64</span><span class="op">></span>();
- <span class="macro">println</span><span class="macro">!</span>(<span class="string">"{}"</span>, <span class="ident">y</span>);
- <span class="kw">if</span> <span class="ident">rand</span>::<span class="ident">random</span>() { <span class="comment">// generates a boolean</span>
- <span class="macro">println</span><span class="macro">!</span>(<span class="string">"Heads!"</span>);
- }</pre>
- <p>This supports generating most common types but is not very flexible, thus
- you probably want to learn a bit more about the Rand library.</p>
- <h1 id="the-two-step-process-to-get-a-random-value" class="section-header"><a href="#the-two-step-process-to-get-a-random-value">The two-step process to get a random value</a></h1>
- <p>Generating random values is typically a two-step process:</p>
- <ul>
- <li>get some <em>random data</em> (an integer or bit/byte sequence) from a random
- number generator (RNG);</li>
- <li>use some function to transform that <em>data</em> into the type of value you want
- (this function is an implementation of some <em>distribution</em> describing the
- kind of value produced).</li>
- </ul>
- <p>Rand represents the first step with the <a href="trait.RngCore.html"><code>RngCore</code></a> trait and the second
- step via a combination of the <a href="trait.Rng.html"><code>Rng</code></a> extension trait and the
- <a href="distributions/index.html"><code>distributions</code> module</a>.
- In practice you probably won't use <a href="trait.RngCore.html"><code>RngCore</code></a> directly unless you are
- implementing a random number generator (RNG).</p>
- <p>There are many kinds of RNGs, with different trade-offs. You can read more
- about them in the <a href="rngs/index.html"><code>rngs</code> module</a> and even more in the <a href="prng/index.html"><code>prng</code> module</a>,
- however, often you can just use <a href="fn.thread_rng.html"><code>thread_rng()</code></a>. This function
- automatically initializes an RNG in thread-local memory, then returns a
- reference to it. It is fast, good quality, and secure (unpredictable).</p>
- <p>To turn the output of the RNG into something usable, you usually want to use
- the methods from the <a href="trait.Rng.html"><code>Rng</code></a> trait. Some of the most useful methods are:</p>
- <ul>
- <li><a href="trait.Rng.html#method.gen"><code>gen</code></a> generates a random value appropriate for the type (just like
- <a href="fn.random.html"><code>random()</code></a>). For integers this is normally the full representable range
- (e.g. from <code>0u32</code> to <code>std::u32::MAX</code>), for floats this is between 0 and 1,
- and some other types are supported, including arrays and tuples. See the
- <a href="distributions/struct.Standard.html"><code>Standard</code></a> distribution which provides the implementations.</li>
- <li><a href="trait.Rng.html#method.gen_range"><code>gen_range</code></a> samples from a specific range of values; this is like
- <a href="trait.Rng.html#method.gen"><code>gen</code></a> but with specific upper and lower bounds.</li>
- <li><a href="trait.Rng.html#method.sample"><code>sample</code></a> samples directly from some distribution.</li>
- </ul>
- <p><a href="fn.random.html"><code>random()</code></a> is defined using just the above: <code>thread_rng().gen()</code>.</p>
- <h2 id="distributions" class="section-header"><a href="#distributions">Distributions</a></h2>
- <p>What are distributions, you ask? Specifying only the type and range of
- values (known as the <em>sample space</em>) is not enough; samples must also have
- a <em>probability distribution</em>, describing the relative probability of
- sampling each value in that space.</p>
- <p>In many cases a <em>uniform</em> distribution is used, meaning roughly that each
- value is equally likely (or for "continuous" types like floats, that each
- equal-sized sub-range has the same probability of containing a sample).
- <a href="trait.Rng.html#method.gen"><code>gen</code></a> and <a href="trait.Rng.html#method.gen_range"><code>gen_range</code></a> both use statistically uniform distributions.</p>
- <p>The <a href="distributions/index.html"><code>distributions</code> module</a> provides implementations
- of some other distributions, including Normal, Log-Normal and Exponential.</p>
- <p>It is worth noting that the functionality already mentioned is implemented
- with distributions: <a href="trait.Rng.html#method.gen"><code>gen</code></a> samples values using the <a href="distributions/struct.Standard.html"><code>Standard</code></a>
- distribution, while <a href="trait.Rng.html#method.gen_range"><code>gen_range</code></a> uses <a href="distributions/struct.Uniform.html"><code>Uniform</code></a>.</p>
- <h2 id="importing-prelude" class="section-header"><a href="#importing-prelude">Importing (prelude)</a></h2>
- <p>The most convenient way to import items from Rand is to use the <a href="prelude/index.html">prelude</a>.
- This includes the most important parts of Rand, but only those unlikely to
- cause name conflicts.</p>
- <p>Note that Rand 0.5 has significantly changed the module organization and
- contents relative to previous versions. Where possible old names have been
- kept (but are hidden in the documentation), however these will be removed
- in the future. We therefore recommend migrating to use the prelude or the
- new module organization in your imports.</p>
- <h2 id="examples" class="section-header"><a href="#examples">Examples</a></h2>
- <pre class="rust rust-example-rendered">
- <span class="kw">use</span> <span class="ident">rand</span>::<span class="ident">prelude</span>::<span class="kw-2">*</span>;
- <span class="comment">// thread_rng is often the most convenient source of randomness:</span>
- <span class="kw">let</span> <span class="kw-2">mut</span> <span class="ident">rng</span> <span class="op">=</span> <span class="ident">thread_rng</span>();
-
- <span class="kw">if</span> <span class="ident">rng</span>.<span class="ident">gen</span>() { <span class="comment">// random bool</span>
- <span class="kw">let</span> <span class="ident">x</span>: <span class="ident">f64</span> <span class="op">=</span> <span class="ident">rng</span>.<span class="ident">gen</span>(); <span class="comment">// random number in range [0, 1)</span>
- <span class="macro">println</span><span class="macro">!</span>(<span class="string">"x is: {}"</span>, <span class="ident">x</span>);
- <span class="kw">let</span> <span class="ident">ch</span> <span class="op">=</span> <span class="ident">rng</span>.<span class="ident">gen</span>::<span class="op"><</span><span class="ident">char</span><span class="op">></span>(); <span class="comment">// using type annotation</span>
- <span class="macro">println</span><span class="macro">!</span>(<span class="string">"char is: {}"</span>, <span class="ident">ch</span>);
- <span class="macro">println</span><span class="macro">!</span>(<span class="string">"Number from 0 to 9: {}"</span>, <span class="ident">rng</span>.<span class="ident">gen_range</span>(<span class="number">0</span>, <span class="number">10</span>));
- }</pre>
- <h1 id="more-functionality" class="section-header"><a href="#more-functionality">More functionality</a></h1>
- <p>The <a href="trait.Rng.html"><code>Rng</code></a> trait includes a few more methods not mentioned above:</p>
- <ul>
- <li><a href="trait.Rng.html#method.sample_iter"><code>Rng::sample_iter</code></a> allows iterating over values from a chosen
- distribution.</li>
- <li><a href="trait.Rng.html#method.gen_bool"><code>Rng::gen_bool</code></a> generates boolean "events" with a given probability.</li>
- <li><a href="trait.Rng.html#method.fill"><code>Rng::fill</code></a> and <a href="trait.Rng.html#method.try_fill"><code>Rng::try_fill</code></a> are fast alternatives to fill a slice
- of integers.</li>
- <li><a href="trait.Rng.html#method.shuffle"><code>Rng::shuffle</code></a> randomly shuffles elements in a slice.</li>
- <li><a href="trait.Rng.html#method.choose"><code>Rng::choose</code></a> picks one element at random from a slice.</li>
- </ul>
- <p>For more slice/sequence related functionality, look in the <a href="seq/index.html"><code>seq</code> module</a>.</p>
- <p>There is also <a href="distributions/struct.WeightedChoice.html"><code>distributions::WeightedChoice</code></a>, which can be used to pick
- elements at random with some probability. But it does not work well at the
- moment and is going through a redesign.</p>
- <h1 id="error-handling" class="section-header"><a href="#error-handling">Error handling</a></h1>
- <p>Error handling in Rand is a compromise between simplicity and necessity.
- Most RNGs and sampling functions will never produce errors, and making these
- able to handle errors would add significant overhead (to code complexity
- and ergonomics of usage at least, and potentially also performance,
- depending on the approach).
- However, external RNGs can fail, and being able to handle this is important.</p>
- <p>It has therefore been decided that <em>most</em> methods should not return a
- <code>Result</code> type, with as exceptions <a href="trait.Rng.html#method.try_fill"><code>Rng::try_fill</code></a>,
- <a href="trait.RngCore.html#method.try_fill_bytes"><code>RngCore::try_fill_bytes</code></a>, and <a href="trait.SeedableRng.html#method.from_rng"><code>SeedableRng::from_rng</code></a>.</p>
- <p>Note that it is the RNG that panics when it fails but is not used through a
- method that can report errors. Currently Rand contains only three RNGs that
- can return an error (and thus may panic), and documents this property:
- <a href="rngs/struct.OsRng.html"><code>OsRng</code></a>, <a href="rngs/struct.EntropyRng.html"><code>EntropyRng</code></a> and <a href="rngs/adapter/struct.ReadRng.html"><code>ReadRng</code></a>. Other RNGs, like <a href="rngs/struct.ThreadRng.html"><code>ThreadRng</code></a>
- and <a href="rngs/struct.StdRng.html"><code>StdRng</code></a>, can be used with all methods without concern.</p>
- <p>One further problem is that if Rand is unable to get any external randomness
- when initializing an RNG with <a href="rngs/struct.EntropyRng.html"><code>EntropyRng</code></a>, it will panic in
- <a href="trait.FromEntropy.html#tymethod.from_entropy"><code>FromEntropy::from_entropy</code></a>, and notably in <a href="fn.thread_rng.html"><code>thread_rng()</code></a>. Except by
- compromising security, this problem is as unsolvable as running out of
- memory.</p>
- <h1 id="distinction-between-rand-and-rand_core" class="section-header"><a href="#distinction-between-rand-and-rand_core">Distinction between Rand and <code>rand_core</code></a></h1>
- <p>The <a href="https://crates.io/crates/rand_core"><code>rand_core</code></a> crate provides the necessary traits and functionality for
- implementing RNGs; this includes the <a href="trait.RngCore.html"><code>RngCore</code></a> and <a href="trait.SeedableRng.html"><code>SeedableRng</code></a> traits
- and the <a href="struct.Error.html"><code>Error</code></a> type.
- Crates implementing RNGs should depend on <a href="https://crates.io/crates/rand_core"><code>rand_core</code></a>.</p>
- <p>Applications and libraries consuming random values are encouraged to use the
- Rand crate, which re-exports the common parts of <a href="https://crates.io/crates/rand_core"><code>rand_core</code></a>.</p>
- <h1 id="more-examples" class="section-header"><a href="#more-examples">More examples</a></h1>
- <p>For some inspiration, see the examples:</p>
- <ul>
- <li><a href="https://github.com/rust-lang-nursery/rand/blob/master/examples/monte-carlo.rs">Monte Carlo estimation of π</a></li>
- <li><a href="https://github.com/rust-lang-nursery/rand/blob/master/examples/monty-hall.rs">Monty Hall Problem</a></li>
- </ul>
- </div><h2 id='modules' class='section-header'><a href="#modules">Modules</a></h2>
- <table>
- <tr class=' module-item'>
- <td><a class="mod" href="distributions/index.html"
- title='mod rand::distributions'>distributions</a></td>
- <td class='docblock-short'>
- <p>Generating random samples from probability distributions.</p>
- </td>
- </tr>
- <tr class=' module-item'>
- <td><a class="mod" href="prelude/index.html"
- title='mod rand::prelude'>prelude</a></td>
- <td class='docblock-short'>
- <p>Convenience re-export of common members</p>
- </td>
- </tr>
- <tr class=' module-item'>
- <td><a class="mod" href="prng/index.html"
- title='mod rand::prng'>prng</a></td>
- <td class='docblock-short'>
- <p>Pseudo-random number generators.</p>
- </td>
- </tr>
- <tr class=' module-item'>
- <td><a class="mod" href="rngs/index.html"
- title='mod rand::rngs'>rngs</a></td>
- <td class='docblock-short'>
- <p>Random number generators and adapters for common usage:</p>
- </td>
- </tr>
- <tr class=' module-item'>
- <td><a class="mod" href="seq/index.html"
- title='mod rand::seq'>seq</a></td>
- <td class='docblock-short'>
- <p>Functions for randomly accessing and sampling sequences.</p>
- </td>
- </tr></table><h2 id='structs' class='section-header'><a href="#structs">Structs</a></h2>
- <table>
- <tr class=' module-item'>
- <td><a class="struct" href="struct.AsciiGenerator.html"
- title='struct rand::AsciiGenerator'>AsciiGenerator</a></td>
- <td class='docblock-short'>
- [<div class='stab deprecated'>Deprecated</div>] <p>Iterator which will continuously generate random ascii characters.</p>
- </td>
- </tr>
- <tr class=' module-item'>
- <td><a class="struct" href="struct.Error.html"
- title='struct rand::Error'>Error</a></td>
- <td class='docblock-short'>
- <p>Error type of random number generators</p>
- </td>
- </tr>
- <tr class=' module-item'>
- <td><a class="struct" href="struct.Generator.html"
- title='struct rand::Generator'>Generator</a></td>
- <td class='docblock-short'>
- [<div class='stab deprecated'>Deprecated</div>] <p>Iterator which will generate a stream of random items.</p>
- </td>
- </tr></table><h2 id='enums' class='section-header'><a href="#enums">Enums</a></h2>
- <table>
- <tr class=' module-item'>
- <td><a class="enum" href="enum.ErrorKind.html"
- title='enum rand::ErrorKind'>ErrorKind</a></td>
- <td class='docblock-short'>
- <p>Error kind which can be matched over.</p>
- </td>
- </tr></table><h2 id='traits' class='section-header'><a href="#traits">Traits</a></h2>
- <table>
- <tr class=' module-item'>
- <td><a class="trait" href="trait.AsByteSliceMut.html"
- title='trait rand::AsByteSliceMut'>AsByteSliceMut</a></td>
- <td class='docblock-short'>
- <p>Trait for casting types to byte slices</p>
- </td>
- </tr>
- <tr class=' module-item'>
- <td><a class="trait" href="trait.CryptoRng.html"
- title='trait rand::CryptoRng'>CryptoRng</a></td>
- <td class='docblock-short'>
- <p>A marker trait used to indicate that an <a href="trait.RngCore.html"><code>RngCore</code></a> or <a href="../rand_core/block/trait.BlockRngCore.html"><code>BlockRngCore</code></a>
- implementation is supposed to be cryptographically secure.</p>
- </td>
- </tr>
- <tr class=' module-item'>
- <td><a class="trait" href="trait.FromEntropy.html"
- title='trait rand::FromEntropy'>FromEntropy</a></td>
- <td class='docblock-short'>
- <p>A convenience extension to <a href="trait.SeedableRng.html"><code>SeedableRng</code></a> allowing construction from fresh
- entropy. This trait is automatically implemented for any PRNG implementing
- <a href="trait.SeedableRng.html"><code>SeedableRng</code></a> and is not intended to be implemented by users.</p>
- </td>
- </tr>
- <tr class=' module-item'>
- <td><a class="trait" href="trait.Rand.html"
- title='trait rand::Rand'>Rand</a></td>
- <td class='docblock-short'>
- [<div class='stab deprecated'>Deprecated</div>] <p>A type that can be randomly generated using an <a href="trait.Rng.html"><code>Rng</code></a>.</p>
- </td>
- </tr>
- <tr class=' module-item'>
- <td><a class="trait" href="trait.Rng.html"
- title='trait rand::Rng'>Rng</a></td>
- <td class='docblock-short'>
- <p>An automatically-implemented extension trait on <a href="trait.RngCore.html"><code>RngCore</code></a> providing high-level
- generic methods for sampling values and other convenience methods.</p>
- </td>
- </tr>
- <tr class=' module-item'>
- <td><a class="trait" href="trait.RngCore.html"
- title='trait rand::RngCore'>RngCore</a></td>
- <td class='docblock-short'>
- <p>The core of a random number generator.</p>
- </td>
- </tr>
- <tr class=' module-item'>
- <td><a class="trait" href="trait.SeedableRng.html"
- title='trait rand::SeedableRng'>SeedableRng</a></td>
- <td class='docblock-short'>
- <p>A random number generator that can be explicitly seeded.</p>
- </td>
- </tr></table><h2 id='functions' class='section-header'><a href="#functions">Functions</a></h2>
- <table>
- <tr class=' module-item'>
- <td><a class="fn" href="fn.random.html"
- title='fn rand::random'>random</a></td>
- <td class='docblock-short'>
- <p>Generates a random value using the thread-local random number generator.</p>
- </td>
- </tr>
- <tr class=' module-item'>
- <td><a class="fn" href="fn.sample.html"
- title='fn rand::sample'>sample</a></td>
- <td class='docblock-short'>
- [<div class='stab deprecated'>Deprecated</div>] <p>DEPRECATED: use <code>seq::sample_iter</code> instead.</p>
- </td>
- </tr>
- <tr class=' module-item'>
- <td><a class="fn" href="fn.thread_rng.html"
- title='fn rand::thread_rng'>thread_rng</a></td>
- <td class='docblock-short'>
- <p>Retrieve the lazily-initialized thread-local random number
- generator, seeded by the system. Intended to be used in method
- chaining style, e.g. <code>thread_rng().gen::<i32>()</code>, or cached locally, e.g.
- <code>let mut rng = thread_rng();</code>.</p>
- </td>
- </tr>
- <tr class=' module-item'>
- <td><a class="fn" href="fn.weak_rng.html"
- title='fn rand::weak_rng'>weak_rng</a></td>
- <td class='docblock-short'>
- [<div class='stab deprecated'>Deprecated</div>] <p>DEPRECATED: use <a href="rngs/struct.SmallRng.html"><code>SmallRng</code></a> instead.</p>
- </td>
- </tr></table></section><section id="search" class="content hidden"></section><section class="footer"></section><aside id="help" class="hidden"><div><h1 class="hidden">Help</h1><div class="shortcuts"><h2>Keyboard Shortcuts</h2><dl><dt><kbd>?</kbd></dt><dd>Show this help dialog</dd><dt><kbd>S</kbd></dt><dd>Focus the search field</dd><dt><kbd>↑</kbd></dt><dd>Move up in search results</dd><dt><kbd>↓</kbd></dt><dd>Move down in search results</dd><dt><kbd>↹</kbd></dt><dd>Switch tab</dd><dt><kbd>⏎</kbd></dt><dd>Go to active search result</dd><dt><kbd>+</kbd></dt><dd>Expand all sections</dd><dt><kbd>-</kbd></dt><dd>Collapse all sections</dd></dl></div><div class="infos"><h2>Search Tricks</h2><p>Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type.</p><p>Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>.</p><p>Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>)</p><p>Search multiple things at once by splitting your query with comma (e.g. <code>str,u8</code> or <code>String,struct:Vec,test</code>)</p></div></div></aside><script>window.rootPath = "../";window.currentCrate = "rand";</script><script src="../aliases.js"></script><script src="../main.js"></script><script defer src="../search-index.js"></script></body></html>
|