Variance.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-1.6.0).
003  * Copyright (c) 2007-2014 Franz Wilhelmstötter
004  *
005  * Licensed under the Apache License, Version 2.0 (the "License");
006  * you may not use this file except in compliance with the License.
007  * You may obtain a copy of the License at
008  *
009  *      http://www.apache.org/licenses/LICENSE-2.0
010  *
011  * Unless required by applicable law or agreed to in writing, software
012  * distributed under the License is distributed on an "AS IS" BASIS,
013  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014  * See the License for the specific language governing permissions and
015  * limitations under the License.
016  *
017  * Author:
018  *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
019  */
020 package org.jenetics.stat;
021 
022 import static java.lang.Double.NaN;
023 import static java.lang.String.format;
024 import static org.jenetics.internal.util.object.eq;
025 
026 import org.jenetics.internal.util.HashBuilder;
027 
028 
029 /**
030  <p>Calculate the variance from a finite sample of <i>N</i> observations.</p>
031  <p><img src="doc-files/variance.gif"
032  *         alt="s^2_{N-1}=\frac{1}{N-1}\sum_{i=1}^{N}\left ( x_i - \bar{x} \right )^2"
033  *    />
034  </p>
035  *
036  <p/>
037  <strong>Note that this implementation is not synchronized.</strong> If
038  * multiple threads access this object concurrently, and at least one of the
039  * threads modifies it, it must be synchronized externally.
040  *
041  @see <a href="http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance" >
042  *       Wikipedia: Algorithms for calculating variance</a>
043  @see <a href="http://mathworld.wolfram.com/Variance.html">
044  *       Wolfram MathWorld: Variance</a>
045  *
046  @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
047  @since 1.0
048  @version 1.0 &mdash; <em>$Date: 2014-03-01 $</em>
049  */
050 public class Variance<N extends Number> extends Mean<N> {
051 
052     private double _m2 = NaN;
053 
054     public Variance() {
055     }
056 
057     /**
058      * Return the variance of the accumulated values.
059      <p><img src="doc-files/variance.gif" alt="Variance" /></p>
060      *
061      @return the variance of the accumulated values, or {@link java.lang.Double#NaN}
062      *          if {@code getSamples() == 0}.
063      */
064     public double getVariance() {
065         double variance = NaN;
066 
067         if (_samples == 1) {
068             variance = _m2;
069         else if (_samples > 1) {
070             variance = _m2/(_samples - 1);
071         }
072 
073         return variance;
074     }
075 
076     /**
077      @throws NullPointerException if the given {@code value} is {@code null}.
078      */
079     @Override
080     public void accumulate(final N value) {
081         if (_samples == 0) {
082             _mean = 0;
083             _m2 = 0;
084         }
085 
086         final double data = value.doubleValue();
087         final double delta = data - _mean;
088 
089         _mean += delta/(++_samples);
090         _m2 += delta*(data - _mean);
091     }
092 
093     @Override
094     public int hashCode() {
095         return HashBuilder.of(getClass()).and(super.hashCode()).and(_m2).value();
096     }
097 
098     @Override
099     public boolean equals(final Object obj) {
100         if (obj == this) {
101             return true;
102         }
103         if (obj == null || getClass() != obj.getClass()) {
104             return false;
105         }
106 
107         final Variance<?> variance = (Variance<?>)obj;
108         return eq(_m2, variance._m2&& super.equals(variance);
109     }
110 
111     @Override
112     public String toString() {
113         return format(
114             "%s[samples=%d, mean=%f, stderr=%f, var=%f]",
115             getClass().getSimpleName(),
116             getSamples(),
117             getMean(),
118             getStandardError(),
119             getVariance()
120         );
121     }
122 
123     @Override
124     public Variance<N> clone() {
125         return (Variance<N>)super.clone();
126     }
127 
128 }