Example usage for org.apache.commons.math3.util MathArrays checkPositive

List of usage examples for org.apache.commons.math3.util MathArrays checkPositive

Introduction

In this page you can find the example usage for org.apache.commons.math3.util MathArrays checkPositive.

Prototype

public static void checkPositive(final double[] in) throws NotStrictlyPositiveException 

Source Link

Document

Check that all entries of the input array are strictly positive.

Usage

From source file:hivemall.utils.math.StatsUtils.java

/**
 * @param observed means non-negative vector
 * @param expected means positive vector
 * @return chi2 value// w  w w. j  av a 2  s. c  o m
 */
public static double chiSquare(@Nonnull final double[] observed, @Nonnull final double[] expected) {
    if (observed.length < 2) {
        throw new DimensionMismatchException(observed.length, 2);
    }
    if (expected.length != observed.length) {
        throw new DimensionMismatchException(observed.length, expected.length);
    }
    MathArrays.checkPositive(expected);
    for (double d : observed) {
        if (d < 0.d) {
            throw new NotPositiveException(d);
        }
    }

    double sumObserved = 0.d;
    double sumExpected = 0.d;
    for (int i = 0; i < observed.length; i++) {
        sumObserved += observed[i];
        sumExpected += expected[i];
    }
    double ratio = 1.d;
    boolean rescale = false;
    if (FastMath.abs(sumObserved - sumExpected) > 10e-6) {
        ratio = sumObserved / sumExpected;
        rescale = true;
    }
    double sumSq = 0.d;
    for (int i = 0; i < observed.length; i++) {
        if (rescale) {
            final double dev = observed[i] - ratio * expected[i];
            sumSq += dev * dev / (ratio * expected[i]);
        } else {
            final double dev = observed[i] - expected[i];
            sumSq += dev * dev / expected[i];
        }
    }
    return sumSq;
}