我正在编写一种方法,以 a*x+b*y=1
的形式计算二维线的方程。
//Given two points, find the equation of the line by solving two linear equations and then test the result. (For simplicity, assume that delta !=0 here)
private boolean solveAndRetry(float x1,float y1, float x2,float y2) {
float delta = x1 * y2 - x2 * y1;
float deltaA = y2 - y1;
float deltaB = x1 - x2;
float a = deltaA / delta;
float b = deltaB / delta;
float c = 1;
//test
if (a * x2 + b * y2 == c) {
System.out.println("ok");
return true;
}
else {
System.out.println(a * x2 + b * y2-c);
return false;
}
}
当我运行它时,我期望所有结果都是“ok”,但事实并非如此,我不知道为什么
public static void main(String[] args) {
for (float x = 0; x < 10; x += 0.01f) {
solveAndRetry(1, -1, x, 2);
}
}
这是结果中的一些行
ok
ok
ok
ok
ok
ok
ok
ok
-5.9604645E-8
ok
-5.9604645E-8
ok
ok
ok
1.1920929E-7
ok
ok
-5.9604645E-8
ok
最佳答案
float
的精度为 6 到 7 位十进制数字。由于舍入误差无法避免,因此您的结果已尽其所能。
通常,您永远不会比较 float 是否相等。始终使用间隔比较,而不是 x == y
:
Math.abs(x - y) < eps
对于适当选择的 eps。
关于java - 浮点精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21063496/