1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
use test::stats::Stats;

/// A structure that helps determine if a value has converged statistically
/// or not.
pub struct Converger {
	/// values are stored in a vector
	vals: Vec<f64>,
	/// max number of values stored
	char_len: usize,
	/// convergence criterion
	epsilon: f64,
	/// number of values ever stored.
	counter: usize,
}

impl Converger {
	pub fn new(char_len: usize, epsilon: f64) -> Self {
		Converger{vals: Vec::<f64>::new(), char_len: char_len, epsilon: epsilon, counter: 0}
	}

	/// Store a value into a vector and increment the number 
	/// of values stored by 1. If the number of values stored is larger
	/// that the characteristic number of values we want to 
	/// perform statistics on, then we remove the extra 
	/// value stored. 
	pub fn take_value(&mut self, val: f64) {
		self.vals.push(val);
		if self.vals.len() > self.char_len {
			self.vals.remove(0);
		}
		self.counter += 1;
		if self.counter % self.char_len == 0 {
			println!("The std dev is = {:?}", self.vals.std_dev());
		}

		assert!(self.vals.len() <= self.char_len, 
			"The number of the stored values must always be smaller that {:?}, and is now {:?}", self.char_len, self.vals.len());
	}

	/// Checks if the value has converged.
	pub fn has_converged(&self) -> bool {
		if self.vals.len() >= self.char_len / 10 {
			self.vals.std_dev() < self.epsilon
		} else {
			false
		}
	}


}