1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.commons.math.stat.descriptive.summary;
17
18 import java.io.Serializable;
19
20 import org.apache.commons.math.stat.descriptive.AbstractStorelessUnivariateStatistic;
21
22 /**
23 * Returns the product of the available values.
24 * <p>
25 * If there are no values in the dataset, or any of the values are
26 * <code>NaN</code>, then <code>NaN</code> is returned.
27 * <p>
28 * <strong>Note that this implementation is not synchronized.</strong> If
29 * multiple threads access an instance of this class concurrently, and at least
30 * one of the threads invokes the <code>increment()</code> or
31 * <code>clear()</code> method, it must be synchronized externally.
32 *
33 * @version $Revision: 348519 $ $Date: 2005-11-23 12:12:18 -0700 (Wed, 23 Nov 2005) $
34 */
35 public class Product extends AbstractStorelessUnivariateStatistic implements Serializable {
36
37 /** Serializable version identifier */
38 private static final long serialVersionUID = 2824226005990582538L;
39
40 /**The number of values that have been added */
41 private long n;
42
43 /**
44 * The current Running Product.
45 */
46 private double value;
47
48 /**
49 * Create a Product instance
50 */
51 public Product() {
52 n = 0;
53 value = Double.NaN;
54 }
55
56 /**
57 * @see org.apache.commons.math.stat.descriptive.StorelessUnivariateStatistic#increment(double)
58 */
59 public void increment(final double d) {
60 if (n == 0) {
61 value = d;
62 } else {
63 value *= d;
64 }
65 n++;
66 }
67
68 /**
69 * @see org.apache.commons.math.stat.descriptive.StorelessUnivariateStatistic#getResult()
70 */
71 public double getResult() {
72 return value;
73 }
74
75 /**
76 * @see org.apache.commons.math.stat.descriptive.StorelessUnivariateStatistic#getN()
77 */
78 public long getN() {
79 return n;
80 }
81
82 /**
83 * @see org.apache.commons.math.stat.descriptive.StorelessUnivariateStatistic#clear()
84 */
85 public void clear() {
86 value = Double.NaN;
87 n = 0;
88 }
89
90 /**
91 * Returns the product of the entries in the specified portion of
92 * the input array, or <code>Double.NaN</code> if the designated subarray
93 * is empty.
94 * <p>
95 * Throws <code>IllegalArgumentException</code> if the array is null.
96 *
97 * @param values the input array
98 * @param begin index of the first array element to include
99 * @param length the number of elements to include
100 * @return the product of the values or Double.NaN if length = 0
101 * @throws IllegalArgumentException if the array is null or the array index
102 * parameters are not valid
103 */
104 public double evaluate(final double[] values, final int begin, final int length) {
105 double product = Double.NaN;
106 if (test(values, begin, length)) {
107 product = 1.0;
108 for (int i = begin; i < begin + length; i++) {
109 product *= values[i];
110 }
111 }
112 return product;
113 }
114
115 }