Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.anhth12.lambda.common.math; import java.util.Collection; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.RealMatrix; /** * * @author Tong Hoang Anh */ public class VectorMath { private VectorMath() { } public static double dot(float[] x, float[] y) { int length = x.length; double dot = 0.0; for (int i = 0; i < length; i++) { dot += (double) x[i] * (double) y[i]; } return dot; } public static double dot(double[] x, float[] y) { int length = x.length; double dot = 0.0; for (int i = 0; i < length; i++) { dot += x[i] * (double) y[i]; } return dot; } public static double norm(float[] x) { double total = 0.0; for (float f : x) { double d = (double) f; total += d * d; } return Math.sqrt(total); } public static RealMatrix transposeTimesSelf(Collection<float[]> M) { if (M == null || M.isEmpty()) { return null; } int features = 0; RealMatrix result = null; for (float[] vector : M) { if (result == null) { features = vector.length; result = new Array2DRowRealMatrix(features, features); } for (int row = 0; row < features; row++) { float rowValue = vector[row]; for (int col = 0; col < features; col++) { result.addToEntry(row, col, rowValue * vector[col]); } } } return result; } public static float[] toFloats(double... doubles) { float[] floats = new float[doubles.length]; for (int i = 0; i < floats.length; i++) { floats[i] = (float) doubles[i]; } return floats; } public static double[] toDoubles(float... floats) { double[] doubles = new double[floats.length]; for (int i = 0; i < doubles.length; i++) { doubles[i] = floats[i]; } return doubles; } public static double[] parseVector(String[] values) { double[] doubles = new double[values.length]; for (int i = 0; i < values.length; i++) { doubles[i] = Double.parseDouble(values[i]); } return doubles; } }