gpt4 book ai didi

java - 2 个 vector 之间的欧氏距离实现

转载 作者:行者123 更新时间:2023-12-01 18:08:26 24 4
gpt4 key购买 nike

我完成了一本学术编程书中的一些练习。任务是实现 2 个 vector 并计算它们之间的欧几里得距离。不,这不是家庭作业,而是自学。

我正在寻求有关我的远程实现的正确性的一些反馈。

public class EuclideanDist
{
public static void main(String[] args)
{
EuclideanDist euc = new EuclideanDist();
Random rnd = new Random();

int N = Integer.parseInt(args[0]);

double[] a = 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 i = 0; i < 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 i = 0; i < 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();
}
}

最佳答案

根据@AlanStokes的建议,以下代码似乎是一种解决方案(我已经测试过):

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[] a = 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) {
for (int i = 0; i < src.length; i++) {
src[i] = rnd.nextDouble();
}
return src;
}

private double distance(double[] a, double[] b) {
double diff_square_sum = 0.0;
for (int i = 0; i < 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) {
for (int j = 0; j < x.length; j++) {
System.out.print(" " + x[j] + " ");
}
System.out.println();
}
}

关于java - 2 个 vector 之间的欧氏距离实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34622466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com