集册 Java实例教程 计算双数组的协方差。

计算双数组的协方差。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

431
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
计算双数组的协方差。


//package com.nowjava;


public class Main {//n o w j a   v  a . c o m - 时  代  Java 提 供

    public static void main(String[] argv) throws Exception {

        double[] v1 = new double[] { 34.45, 35.45, 36.67, 37.78, 37.0000,

                37.1234, 67.2344, 68.34534, 69.87700 };

        double[] v2 = new double[] { 34.45, 35.45, 36.67, 37.78, 37.0000,

                37.1234, 67.2344, 68.34534, 69.87700 };

        System.out.println(covariance(v1, v2));

    }


    /**

     * Computes the covariance.

     */

    public static double covariance(double[] v1, double[] v2) {

        if (v1.length != v2.length)

            throw new IllegalArgumentException(

                    "Arrays must have the same length : " + v1.length

                            + ", " + v2.length);

        final double m1 = mean(v1);

        final double m2 = mean(v2);
        /**
         * 时 代 J     a    v  a - nowjava.com 提 供 
        **/

        double ans = 0.0;

        for (int i = 0; i < v1.length; i++)

            ans += (v1[i] - m1) * (v2[i] - m2);

        return ans / (v1.length - 1);

    }


    /**

     * Computes the covariance.

     */

    public static double covariance(int[] v1, int[] v2) {

        if (v1.length != v2.length)

            throw new IllegalArgumentException(

                    "Arrays must have the same length : " + v1.length

                            + ", " + v2.length);

        final double m1 = mean(v1);

        final double m2 = mean(v2);

        double ans = 0.0;

        for (int i = 0; i < v1.length; i++)

            ans += (v1[i] - m1) * (v2[i] - m2);

        return ans / (v1.length - 1);

    }


    /**

     * Computes the mean.

     */

    public static double mean(double[] v) {

        if (v.length == 0)

            throw new IllegalArgumentException(

                    "Nothing to compute! The array must have at least one element.");

        return (mass(v) / (double) v.length);

    }


    /**

     * Computes the mean.

     */

    public static double mean(int[] v) {

        if (v.length == 0)

            throw new IllegalArgumentException(

                    "Nothing to compute! The array must have at least one element.");

        return (mass(v) / (double) v.length);

    }


    /**

     * Returns the sum of the elements of the array.

     */

    public static double m
展开阅读全文