java - Euclidean Distance between 2 Vectors Implementation -
i working through few exercises academic programing book. task implement 2 vectors , calculate euclidean distance between thereof. no not home work, rather self studying.
i'm seeking feedback on correctness of distance implementation.
public class euclideandist { public static void main(string[] args) { euclideandist euc = new euclideandist(); random rnd = new random(); int n = integer.parseint(args[0]); double[] = new double[n]; double[] b = new double[n]; double[] x = new double[n]; euc.print(euc.init(a, rnd)); euc.print(euc.init(b, rnd)); print(euc.distance(a, b, x)); } private double[] init(double[] src, random rnd) { for(int = 0; < src.length; i++) { src[i] = rnd.nextdouble(); } return src; } private double[] distance(double[] a, double[] b, double[] x) { double diff; int n = a.length; for(int = 0; < n; i++) { diff = a[i] - b[i]; x[i] = math.sqrt(diff * diff); } return x; } private static void print(double[] x) { int n = x.length; for(int j = 0; j < n; j++) system.out.print(" " + x[j] + " "); system.out.println(); } }
based on suggestions of @alanstokes, following codes seems 1 solution (i have tested it):
import java.util.random; public class euclideandist { public static void main(string[] args) { euclideandist euc = new euclideandist(); random rnd = new random(); int n = integer.parseint(args[0]); double[] = new double[n]; double[] b = new double[n]; euc.print(euc.init(a, rnd)); euc.print(euc.init(b, rnd)); system.out.println(euc.distance(a, b)); } private double[] init(double[] src, random rnd) { (int = 0; < src.length; i++) { src[i] = rnd.nextdouble(); } return src; } private double distance(double[] a, double[] b) { double diff_square_sum = 0.0; (int = 0; < a.length; i++) { diff_square_sum += (a[i] - b[i]) * (a[i] - b[i]); } return math.sqrt(diff_square_sum); } private void print(double[] x) { (int j = 0; j < x.length; j++) { system.out.print(" " + x[j] + " "); } system.out.println(); } }
Comments
Post a Comment