對于下面的問題,是否是我如此接近零,但將零與容差進行比較不起作用?數字越精確,我對直線上圓弧點的檢查就越失敗,而越不精確,它就越有效。CAD 繪圖確實有一個弧線,該弧線在線段上有一個點,這就是我在此測試中獲取輸入坐標的地方。class Line{ public Point Point1 {get;set;} public Point Point2 {get;set;} public Line(double x1, double y1, double x2, double y2) { Point1 = new Point(x1,y1); Point2 = new Point(x2,y2); }}class Point{ public double X {get;set;} public double Y {get;set;} public Point (double x, double y) { X = x; Y = y; }}//4 decimal place numbers, worksPoint arcEnd = new Point(3.8421, 16.9538); // these numbers don't //3.84212141717697, //16.9538136440052Point arcStart = new Point(4.0921, 17.2038);//test an arc point on/off the lineLine line = new Line(3.9336, 16.9538, 3.7171, 16.9538); //these numbers don't 3.93362776812308, 16.9538136440053, //3.71712141717697, 16.9538136440054bool on_line = Sign(line.Point1, line.Point2, arcEnd) //true//more precise numbers, from CAD / dxf drawing for line and arc, arc end //point touches somewhere on the line (included in comments above, fail)//so on_line = true for the above inputs and the Sign function gives zero, //but when using the commented precise numbers sign gives back 1 and the //value computed in sign is 3.0639866299190109E-14.public static bool Sign(Point Point1, Point Point2, Point point){ double value = (Point2.X - Point1.X) * (p.Y - Point1.Y) - (Point2.Y - Point1.Y) * (p.X - Point1.X); return Equals(Math.Sign(value), 0);}public static bool Equals(double d1, double d2, double tolerance=0.000001){ double a = Math.Abs(d1 - d2); double b = Math.Abs(d1 * tolerance); if (a <= b) { return true; } return false;}檢查了公式和堆棧溢出,該算法在大多數情況下都有效,但發現它失敗的情況,我將其追溯到包含的示例,并確定我的檢查針對上述輸入返回 Sign = 1 而不是 Sign = 0,并且精度更高。
1 回答

楊魅力
TA貢獻1811條經驗 獲得超6個贊
你犯了兩個錯誤。首先,您在“Return Equals(Math.Sign(value), 0);”中使用了 Sign 函數,它將為任何正數提供 1 的值,為任何負數提供 -1 的值。這會破壞你使用寬容的嘗試。其次,您嘗試將差異與第一個數字“b = Math.Abs(d1 * 容差)”的比率進行比較,這將始終返回 False。我建議你將它與寬容本身進行比較,就像這樣。
public static bool Sign(Point Point1, Point Point2, Point point)
{
double value = (Point2.X - Point1.X) * (point.Y - Point1.Y) - (Point2.Y - Point1.Y) * (point.X - Point1.X);
return Equals(value, 0);
}
public static bool Equals(double d1, double d2, double tolerance = 0.000001)
{
double a = Math.Abs(d1 - d2);
if (a <= tolerance)
return true;
return false;
}
- 1 回答
- 0 關注
- 101 瀏覽
添加回答
舉報
0/150
提交
取消