Java mean meanFast(final double[] values)

Here you can find the source of meanFast(final double[] values)

Description

mean Fast

License

Open Source License

Declaration

public final static double meanFast(final double[] values) 

Method Source Code

//package com.java2s;
/*/*  w  w w. j a v a 2 s. c o  m*/
 * ====================================================
 * Copyright (C) 2013 by Idylwood Technologies, LLC. All rights reserved.
 *
 * Developed at Idylwood Technologies, LLC.
 * Permission to use, copy, modify, and distribute this
 * software is freely granted, provided that this notice
 * is preserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * The License should have been distributed to you with the source tree.
 * If not, it can be found at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author: Charles Cooper
 * Date: 2013
 * ====================================================
 */

public class Main {
    public final static double meanFast(final double[] values) {
        return sumFast(values) / values.length;
    }

    /**
     * Numerically naive implementation of sum which is faster than MathUtils.sum() and sumNaive()
     * Generally exhibits rounding error which grows with the length of the sum
     * Note that it may not agree with other implementations
     * due to optimizations which change the order of iteration
     * which can affect the rounding error.
     * It is O(n) in the length of the array to be summed.
     * It is faster than the naive, unoptimized implementation by 20-40%
     * (dependent on the mood of the JIT) on my machine.
     * @param values
     * @return
     * Side Effects: none
     */
    public static final double sumFast(final double... values) {
        double ret = 0;
        // unroll the loop since the JIT shouldn't
        final int unroll = 4; // empirically unrolling more than 3 doesn't help much
        final int len = values.length - values.length % unroll;
        int i = 0;
        for (; i < len; i += unroll)
            ret += values[i] + values[i + 1] + values[i + 2] + values[i + 3];
        for (; i < values.length; i++)
            ret += values[i];
        return ret;
    }
}

Related

  1. meanAndVariance(double[] a, boolean useUnbiasedEstimate)
  2. meanArithmetic(LinkedList a)
  3. meanArray(double[] arr)
  4. meandiff(double[] v1, double[] v2)
  5. meanEnt(double[] nums)
  6. meanFilter(float[] weights, int context)
  7. meanGreenwichSideralTime(double t)
  8. meanImage(float[][]... images)
  9. meanLow(final int a, final int b)