9
9
10
10
//! The Cauchy distribution.
11
11
12
- use crate :: utils :: Float ;
12
+ use num_traits :: { Float , FloatConst } ;
13
13
use crate :: { Distribution , Standard } ;
14
14
use rand:: Rng ;
15
- use std :: { error , fmt} ;
15
+ use core :: fmt;
16
16
17
17
/// The Cauchy distribution `Cauchy(median, scale)`.
18
18
///
@@ -52,30 +52,31 @@ impl fmt::Display for Error {
52
52
}
53
53
}
54
54
55
- impl error:: Error for Error { }
55
+ #[ cfg( feature = "std" ) ]
56
+ impl std:: error:: Error for Error { }
56
57
57
- impl < N : Float > Cauchy < N >
58
+ impl < N : Float + FloatConst > Cauchy < N >
58
59
where Standard : Distribution < N >
59
60
{
60
61
/// Construct a new `Cauchy` with the given shape parameters
61
62
/// `median` the peak location and `scale` the scale factor.
62
63
pub fn new ( median : N , scale : N ) -> Result < Cauchy < N > , Error > {
63
- if !( scale > N :: from ( 0.0 ) ) {
64
+ if !( scale > N :: zero ( ) ) {
64
65
return Err ( Error :: ScaleTooSmall ) ;
65
66
}
66
67
Ok ( Cauchy { median, scale } )
67
68
}
68
69
}
69
70
70
- impl < N : Float > Distribution < N > for Cauchy < N >
71
+ impl < N : Float + FloatConst > Distribution < N > for Cauchy < N >
71
72
where Standard : Distribution < N >
72
73
{
73
74
fn sample < R : Rng + ?Sized > ( & self , rng : & mut R ) -> N {
74
75
// sample from [0, 1)
75
76
let x = Standard . sample ( rng) ;
76
77
// get standard cauchy random number
77
78
// note that π/2 is not exactly representable, even if x=0.5 the result is finite
78
- let comp_dev = ( N :: pi ( ) * x) . tan ( ) ;
79
+ let comp_dev = ( N :: PI ( ) * x) . tan ( ) ;
79
80
// shift and scale according to parameters
80
81
self . median + self . scale * comp_dev
81
82
}
@@ -108,10 +109,12 @@ mod test {
108
109
sum += numbers[ i] ;
109
110
}
110
111
let median = median ( & mut numbers) ;
111
- println ! ( "Cauchy median: {}" , median) ;
112
+ #[ cfg( feature = "std" ) ]
113
+ std:: println!( "Cauchy median: {}" , median) ;
112
114
assert ! ( ( median - 10.0 ) . abs( ) < 0.4 ) ; // not 100% certain, but probable enough
113
115
let mean = sum / 1000.0 ;
114
- println ! ( "Cauchy mean: {}" , mean) ;
116
+ #[ cfg( feature = "std" ) ]
117
+ std:: println!( "Cauchy mean: {}" , mean) ;
115
118
// for a Cauchy distribution the mean should not converge
116
119
assert ! ( ( mean - 10.0 ) . abs( ) > 0.4 ) ; // not 100% certain, but probable enough
117
120
}
@@ -130,7 +133,7 @@ mod test {
130
133
131
134
#[ test]
132
135
fn value_stability ( ) {
133
- fn gen_samples < N : Float + core:: fmt:: Debug > ( m : N , s : N , buf : & mut [ N ] )
136
+ fn gen_samples < N : Float + FloatConst + core:: fmt:: Debug > ( m : N , s : N , buf : & mut [ N ] )
134
137
where Standard : Distribution < N > {
135
138
let distr = Cauchy :: new ( m, s) . unwrap ( ) ;
136
139
let mut rng = crate :: test:: rng ( 353 ) ;
0 commit comments