gpt4 book ai didi

java - 如何确定两个数学 vector 是否相同?

转载 作者:行者123 更新时间:2023-12-01 18:49:46 25 4
gpt4 key购买 nike

我需要确定两个 vector 是否几乎相等(相似)。如果两个 vector 的 vector 差值的大小小于指定的容差 (tol) other - 要比较的另一个 vector 与 vector 差值的阈值长度 (this - other) 返回 true,如果 (this - other) 的长度) 小于 tol,否则为 false。

这是我的方法:

public boolean similarTo(Vector2 other, double tol) {
boolean result = false;
double z = this.mag() - other.mag();
if (z < tol) {
result = true;
}
else {
result = false;
}
return result;
}

但是,这似乎不起作用,因为当我运行 JUnit 测试时,我得到一个 java.lang.AssertionError,没有其他错误。任何帮助,将不胜感激。顺便说一句,mag() 方法已经编写并且可以正常工作。

编辑:这是 JUnit 测试:

@Test
public void test15_similarTo() {
double rad = 0.34;
double x = Math.cos(rad);
double y = Math.sin(rad);
Vector2 unit = new Vector2(x, y);
for (int i = -6; i <= 6; i++) {
double tol = Math.pow(10.0, i);

// if we scale unit by maxScale we will be at the limits of similarity
double maxScale = 1.0 + tol;
double scale = Math.nextAfter(maxScale, Double.NEGATIVE_INFINITY);
Vector2 w = new Vector2(scale * x, scale * y);
assertTrue(unit.similarTo(w, tol));

scale = Math.nextAfter(maxScale, Double.POSITIVE_INFINITY);
w = new Vector2(scale * x, scale * y);
assertFalse(unit.similarTo(w, tol));
}
}

最佳答案

这是解决方案(对于任何感兴趣的人):

public boolean similarTo(Vector2 other, double tol) {
boolean result = false;
double z = Math.abs(this.mag() - other.mag());
if (z < tol) {
result = true;
}
else {
result = false;
}
return result;
}

关于java - 如何确定两个数学 vector 是否相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59759639/

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