2D直線の方程式を次の形式で計算するメソッドを書いています。 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
Afloat
の精度は10進数で6〜7桁です。丸め誤差は避けられないため、結果は可能な限り良好です。
通常、浮動小数点数が等しいかどうかを比較することはありません。x == y
常に間隔を使用して比較を使用する代わりに、次のようにします。
Math.abs(x - y) < eps
適切に選択されたepsの場合。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加