]>
git.proxmox.com Git - rustc.git/blob - vendor/rand/src/distributions/cauchy.rs
1 // Copyright 2018 Developers of the Rand project.
2 // Copyright 2016-2017 The Rust Project Developers.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 //! The Cauchy distribution.
12 #![allow(clippy::all)]
14 use crate::distributions
::Distribution
;
16 use std
::f64::consts
::PI
;
18 /// The Cauchy distribution `Cauchy(median, scale)`.
20 /// This distribution has a density function:
21 /// `f(x) = 1 / (pi * scale * (1 + ((x - median) / scale)^2))`
22 #[deprecated(since = "0.7.0", note = "moved to rand_distr crate")]
23 #[derive(Clone, Copy, Debug)]
30 /// Construct a new `Cauchy` with the given shape parameters
31 /// `median` the peak location and `scale` the scale factor.
32 /// Panics if `scale <= 0`.
33 pub fn new(median
: f64, scale
: f64) -> Cauchy
{
34 assert
!(scale
> 0.0, "Cauchy::new called with scale factor <= 0");
35 Cauchy { median, scale }
39 impl Distribution
<f64> for Cauchy
{
40 fn sample
<R
: Rng
+ ?Sized
>(&self, rng
: &mut R
) -> f64 {
42 let x
= rng
.gen
::<f64>();
43 // get standard cauchy random number
44 // note that π/2 is not exactly representable, even if x=0.5 the result is finite
45 let comp_dev
= (PI
* x
).tan();
46 // shift and scale according to parameters
47 let result
= self.median
+ self.scale
* comp_dev
;
55 use crate::distributions
::Distribution
;
57 fn median(mut numbers
: &mut [f64]) -> f64 {
59 let mid
= numbers
.len() / 2;
63 fn sort(numbers
: &mut [f64]) {
64 numbers
.sort_by(|a
, b
| a
.partial_cmp(b
).unwrap());
68 fn test_cauchy_averages() {
69 // NOTE: given that the variance and mean are undefined,
70 // this test does not have any rigorous statistical meaning.
71 let cauchy
= Cauchy
::new(10.0, 5.0);
72 let mut rng
= crate::test
::rng(123);
73 let mut numbers
: [f64; 1000] = [0.0; 1000];
76 numbers
[i
] = cauchy
.sample(&mut rng
);
79 let median
= median(&mut numbers
);
80 println
!("Cauchy median: {}", median
);
81 assert
!((median
- 10.0).abs() < 0.4); // not 100% certain, but probable enough
82 let mean
= sum
/ 1000.0;
83 println
!("Cauchy mean: {}", mean
);
84 // for a Cauchy distribution the mean should not converge
85 assert
!((mean
- 10.0).abs() > 0.4); // not 100% certain, but probable enough
90 fn test_cauchy_invalid_scale_zero() {
91 Cauchy
::new(0.0, 0.0);
96 fn test_cauchy_invalid_scale_neg() {
97 Cauchy
::new(0.0, -10.0);