Commit d6247856 authored by Tim McNamara's avatar Tim McNamara

Expand rust/logistic-map.md

parent acea01ae
This snippet of code demonstrates how to create an infinitely long `Iterator`
for a iterated function. A data structure stores some state, in this case `x`,
This example demonstrates how to create an infinitely long `Iterator`
for a [iterated function][]. We're using'a [logistic map][] as our function, for three reasons:
- it's very simple
- it's the gateway drug into chaos theory
- with certain parameters, it can be used to simulate a random number generator
[iterated function]: https://en.wikipedia.org/wiki/Iterated_function
[logistic map]: https://en.wikipedia.org/wiki/Logistic_map
All you need is a data structure stores some state, in this case `x`,
that is then fed into the actual function at each step.
## Example 1: Implementing the logistic map as a Rust iterator
```rust
fn logistic_map(x: f64, r: f64) -> f64 {
x * r * (1.0 - x)
......@@ -26,4 +40,35 @@ fn main() {
let res: Vec<f64> = LogisticMap{r: 3.995, x: 0.5}.take(20).collect();
println!("{:#?}", res);
}
```
\ No newline at end of file
```
Output ([Try yourself][example-1])
>
> ```rust
> [
> 0.99875,
> 0.004987507812499894,
> 0.019825717150388986,
> 0.07763346906899773,
> 0.2860680216294963,
> 0.815911268978777,
> 0.6000492801782142,
> 0.9587606154356058,
> 0.15795709741195127,
> 0.5313615778926247,
> 0.994820723471179,
> 0.02058404423571871,
> 0.08054056372768964,
> 0.2958448563818518,
> 0.8322411059503418,
> 0.5577653108299905,
> 0.9854193596145349,
> 0.05740034101910245,
> 0.21615163977062282,
> 0.6768732830383994
> ]
> ```
[example-1]: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&code=fn%20logistic_map(x%3A%20f64%2C%20r%3A%20f64)%20-%3E%20f64%20%7B%0A%20%20%20%20x%20*%20r%20*%20(1.0%20-%20x)%0A%7D%0A%20%20%20%0Astruct%20LogisticMap%20%7B%0A%20%20%20%20r%3A%20f64%2C%0A%20%20%20%20x%3A%20f64%2C%0A%7D%0A%0Aimpl%20Iterator%20for%20LogisticMap%20%7B%0A%20%20%20%20type%20Item%20%3D%20f64%3B%0A%20%20%20%20%0A%20%20%20%20fn%20next(%26mut%20self)%20-%3E%20Option%3CSelf%3A%3AItem%3E%20%7B%0A%20%20%20%20%20%20%20%20let%20new_x%20%3D%20logistic_map(self.x%2C%20self.r)%3B%0A%20%20%20%20%20%20%20%20self.x%20%3D%20new_x%3B%0A%20%20%20%20%20%20%20%20Some(new_x)%0A%20%20%20%20%7D%20%0A%7D%0A%0Afn%20main()%20%7B%0A%20%20%20%20let%20res%3A%20Vec%3Cf64%3E%20%3D%20LogisticMap%7Br%3A%203.995%2C%20x%3A%200.5%7D.take(20).collect()%3B%0A%20%20%20%20println!(%22%7B%3A%23%3F%7D%22%2C%20res)%3B%0A%7D
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment