Skip to content

Commit b264f38

Browse files
authored
Merge pull request #328 from dhardy/readme
Update READMEs.
2 parents 0a3c38d + 5271ffb commit b264f38

File tree

9 files changed

+439
-261
lines changed

9 files changed

+439
-261
lines changed

.travis.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ matrix:
3333
- cargo test --all --features=alloc
3434
- cargo test --features serde-1,log,nightly
3535
- cargo test --benches
36-
- cargo doc --no-deps --all-features
36+
- cargo doc --no-deps --all --all-features
3737
after_success:
3838
- travis-cargo --only nightly doc-upload
3939

README.md

+32-25
Original file line numberDiff line numberDiff line change
@@ -3,24 +3,34 @@ Rand
33

44
A Rust library for random number generators and other randomness functionality.
55

6+
See also:
7+
8+
* [rand_core](https://crates.io/crates/rand_core)
9+
610
[![Build Status](https://travis-ci.org/rust-lang-nursery/rand.svg?branch=master)](https://travis-ci.org/rust-lang-nursery/rand)
711
[![Build status](https://ci.appveyor.com/api/projects/status/rm5c9o33k3jhchbw?svg=true)](https://ci.appveyor.com/project/alexcrichton/rand)
812

9-
[Documentation](https://docs.rs/rand)
13+
Documentation:
14+
[master branch](https://rust-lang-nursery.github.io/rand/rand/index.html),
15+
[by release](https://docs.rs/rand)
1016

1117
## Usage
1218

1319
Add this to your `Cargo.toml`:
1420

1521
```toml
1622
[dependencies]
17-
rand = "0.4"
23+
rand = "0.5.0-pre.0"
1824
```
1925

2026
and this to your crate root:
2127

2228
```rust
2329
extern crate rand;
30+
31+
// example usage:
32+
use rand::{Rng, thread_rng};
33+
let x: f64 = thread_rng().gen();
2434
```
2535

2636
## Versions
@@ -44,34 +54,31 @@ Travis CI always has a build with a pinned version of Rustc matching the oldest
4454
supported Rust release. The current policy is that this can be updated in any
4555
Rand release if required, but the change must be noted in the changelog.
4656

47-
## Examples
48-
49-
There is built-in support for a random number generator (RNG) associated with each thread stored in thread-local storage. This RNG can be accessed via thread_rng, or used implicitly via random. This RNG is normally randomly seeded from an operating-system source of randomness, e.g. /dev/urandom on Unix systems, and will automatically reseed itself from this source after generating 32 KiB of random data.
50-
51-
```rust
52-
let tuple = rand::random::<(f64, char)>();
53-
println!("{:?}", tuple)
54-
```
55-
56-
```rust
57-
use rand::Rng;
57+
## Functionality
5858

59-
let mut rng = rand::thread_rng();
60-
if rng.gen() { // random bool
61-
println!("i32: {}, u32: {}", rng.gen::<i32>(), rng.gen::<u32>())
62-
}
63-
```
59+
The `rand_core` crate provides:
6460

65-
It is also possible to use other RNG types, which have a similar interface. The following uses the "ChaCha" algorithm instead of the default.
61+
- base random number generator traits
62+
- error-reporting types
63+
- functionality to aid implementation of RNGs
6664

67-
```rust
68-
use rand::{Rng, ChaChaRng};
65+
The `rand` crate provides:
6966

70-
let mut rng = rand::ChaChaRng::new_unseeded();
71-
println!("i32: {}, u32: {}", rng.gen::<i32>(), rng.gen::<u32>())
72-
```
67+
- most content from `rand_core` (re-exported)
68+
- fresh entropy: `EntropyRng`, `OsRng`, `JitterRng`
69+
- pseudo-random number generators: `StdRng`, `SmallRng`, `prng` module
70+
- convenient, auto-seeded crypto-grade thread-local generator: `thread_rng`
71+
- `distributions` producing many different types of random values:
72+
- `Uniform`-ly distributed integers and floats of many types
73+
- unbiased sampling from specified `Range`s
74+
- sampling from exponential/normal/gamma distributions
75+
- sampling from binomial/poisson distributions
76+
- `gen_bool` aka Bernoulli distribution
77+
- `seq`-uence related functionality:
78+
- sampling a subset of elements
79+
- randomly shuffling a list
7380

74-
## Features
81+
## Crate Features
7582

7683
By default, Rand is built with all stable features available. The following
7784
optional features are available:

examples/monte-carlo.rs

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Copyright 2013-2018 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// https://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
//! # Monte Carlo estimation of π
12+
//!
13+
//! Imagine that we have a square with sides of length 2 and a unit circle
14+
//! (radius = 1), both centered at the origin. The areas are:
15+
//!
16+
//! ```text
17+
//! area of circle = πr² = π * r * r = π
18+
//! area of square = 2² = 4
19+
//! ```
20+
//!
21+
//! The circle is entirely within the square, so if we sample many points
22+
//! randomly from the square, roughly π / 4 of them should be inside the circle.
23+
//!
24+
//! We can use the above fact to estimate the value of π: pick many points in
25+
//! the square at random, calculate the fraction that fall within the circle,
26+
//! and multiply this fraction by 4.
27+
28+
#![cfg(feature="std")]
29+
30+
31+
extern crate rand;
32+
33+
use rand::distributions::{Distribution, Range};
34+
35+
fn main() {
36+
let range = Range::new(-1.0f64, 1.0);
37+
let mut rng = rand::thread_rng();
38+
39+
let total = 1_000_000;
40+
let mut in_circle = 0;
41+
42+
for _ in 0..total {
43+
let a = range.sample(&mut rng);
44+
let b = range.sample(&mut rng);
45+
if a*a + b*b <= 1.0 {
46+
in_circle += 1;
47+
}
48+
}
49+
50+
// prints something close to 3.14159...
51+
println!("π is approximately {}", 4. * (in_circle as f64) / (total as f64));
52+
}

examples/monty-hall.rs

+118
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
// Copyright 2013-2018 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// https://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
//! ## Monty Hall Problem
12+
//!
13+
//! This is a simulation of the [Monty Hall Problem][]:
14+
//!
15+
//! > Suppose you're on a game show, and you're given the choice of three doors:
16+
//! > Behind one door is a car; behind the others, goats. You pick a door, say
17+
//! > No. 1, and the host, who knows what's behind the doors, opens another
18+
//! > door, say No. 3, which has a goat. He then says to you, "Do you want to
19+
//! > pick door No. 2?" Is it to your advantage to switch your choice?
20+
//!
21+
//! The rather unintuitive answer is that you will have a 2/3 chance of winning
22+
//! if you switch and a 1/3 chance of winning if you don't, so it's better to
23+
//! switch.
24+
//!
25+
//! This program will simulate the game show and with large enough simulation
26+
//! steps it will indeed confirm that it is better to switch.
27+
//!
28+
//! [Monty Hall Problem]: https://en.wikipedia.org/wiki/Monty_Hall_problem
29+
30+
#![cfg(feature="std")]
31+
32+
33+
extern crate rand;
34+
35+
use rand::Rng;
36+
use rand::distributions::{Distribution, Range};
37+
use rand::distributions::range::RangeInt;
38+
39+
struct SimulationResult {
40+
win: bool,
41+
switch: bool,
42+
}
43+
44+
// Run a single simulation of the Monty Hall problem.
45+
fn simulate<R: Rng>(random_door: &Range<RangeInt<u32>>, rng: &mut R)
46+
-> SimulationResult {
47+
let car = random_door.sample(rng);
48+
49+
// This is our initial choice
50+
let mut choice = random_door.sample(rng);
51+
52+
// The game host opens a door
53+
let open = game_host_open(car, choice, rng);
54+
55+
// Shall we switch?
56+
let switch = rng.gen();
57+
if switch {
58+
choice = switch_door(choice, open);
59+
}
60+
61+
SimulationResult { win: choice == car, switch: switch }
62+
}
63+
64+
// Returns the door the game host opens given our choice and knowledge of
65+
// where the car is. The game host will never open the door with the car.
66+
fn game_host_open<R: Rng>(car: u32, choice: u32, rng: &mut R) -> u32 {
67+
let choices = free_doors(&[car, choice]);
68+
rand::seq::sample_slice(rng, &choices, 1)[0]
69+
}
70+
71+
// Returns the door we switch to, given our current choice and
72+
// the open door. There will only be one valid door.
73+
fn switch_door(choice: u32, open: u32) -> u32 {
74+
free_doors(&[choice, open])[0]
75+
}
76+
77+
fn free_doors(blocked: &[u32]) -> Vec<u32> {
78+
(0..3).filter(|x| !blocked.contains(x)).collect()
79+
}
80+
81+
fn main() {
82+
// The estimation will be more accurate with more simulations
83+
let num_simulations = 10000;
84+
85+
let mut rng = rand::thread_rng();
86+
let random_door = Range::new(0u32, 3);
87+
88+
let (mut switch_wins, mut switch_losses) = (0, 0);
89+
let (mut keep_wins, mut keep_losses) = (0, 0);
90+
91+
println!("Running {} simulations...", num_simulations);
92+
for _ in 0..num_simulations {
93+
let result = simulate(&random_door, &mut rng);
94+
95+
match (result.win, result.switch) {
96+
(true, true) => switch_wins += 1,
97+
(true, false) => keep_wins += 1,
98+
(false, true) => switch_losses += 1,
99+
(false, false) => keep_losses += 1,
100+
}
101+
}
102+
103+
let total_switches = switch_wins + switch_losses;
104+
let total_keeps = keep_wins + keep_losses;
105+
106+
println!("Switched door {} times with {} wins and {} losses",
107+
total_switches, switch_wins, switch_losses);
108+
109+
println!("Kept our choice {} times with {} wins and {} losses",
110+
total_keeps, keep_wins, keep_losses);
111+
112+
// With a large number of simulations, the values should converge to
113+
// 0.667 and 0.333 respectively.
114+
println!("Estimated chance to win if we switch: {}",
115+
switch_wins as f32 / total_switches as f32);
116+
println!("Estimated chance to win if we don't: {}",
117+
keep_wins as f32 / total_keeps as f32);
118+
}

rand_core/README.md

+23-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,29 @@ prefer to use the main [rand] crate.
1616

1717
[Documentation](https://docs.rs/rand_core)
1818

19-
[rand]: ../README.md
19+
[rand]: https://crates.io/crates/rand
20+
21+
22+
## Functionality
23+
24+
The `rand_core` crate provides:
25+
26+
- base random number generator traits
27+
- error-reporting types
28+
- functionality to aid implementation of RNGs
29+
30+
The traits and error types are also available via `rand`.
31+
32+
## Crate Features
33+
34+
`rand_core` supports `no_std` and `alloc`-only configurations, as well as full
35+
`std` functionality. The differences between `no_std` and full `std` are small,
36+
comprising `RngCore` support for `Box<R>` types where `R: RngCore`, as well as
37+
extensions to the `Error` type's functionality.
38+
39+
Due to a bug in Cargo, `rand_core` is built without `std` support by default.
40+
Since features are unioned across the whole dependency tree, any crate using
41+
`rand` with its default features will also enable `std` support in `rand_core`.
2042

2143

2244
# License

0 commit comments

Comments
 (0)