集册 Java实例教程 计算数组的L2范数(欧几里德范数或“长度”)。

计算数组的L2范数(欧几里德范数或“长度”)。

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

129
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
计算数组的L2范数(欧几里德范数或“长度”)。
/* 
*来 自
 N  o w  J a v a . c o m
*/


//package com.nowjava;


public class Main {

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

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

                37.1234, 67.2344, 68.34534, 69.87700 };

        System.out.println(norm(data));

    }


    /**

     * Computes the L2 norm of an array (Euclidean norm or "length").

     */

    public static double norm(double[] data) {

        return (Math.sqrt(sumSquares(data)));

    }


    /**

     * Computes the L2 norm of an array (Euclidean norm or "length").

     */
     /*
      from N  o w  J a v a . c o m 
     */

    public static double norm(int[] data) {

        return (Math.sqrt(sumSquares(data)));

    }


    /**

     * Sums the squares of all components;

     * also called the energy of the array.

     */

    public static double sumSquares(double[] data) {

        double ans = 0.0;

        for (int k = 0; k < data.length; k++) {

            ans += data[k] * data[k];

        }

        return (ans);

    }


    /**

     * Sums the squares of all components;

     * also called the energy of the array.

     */

    public static double sumSquares(double[][] data) {

        double ans = 0.0;

        for (int k = 0; k < data.length; k++) {

            for (int l = 0; l < data[k].length; l++) {

                ans += data[k][l] * data[k][l];

            }

        }

        return (ans);

    }


    /**

     * Sums the squares of all components;

     * also called the energy of the array.

     */

    public static int sumSquares(int[] data) {

        int ans = 0;

        for (int k = 0; k < data.length; k++) {

            ans += data[k] * data[k];

        }

        return (ans);

    }


    
展开阅读全文