簡體   English   中英

避免算法中的浮點精度錯誤

[英]Avoid floating-point precision error in algorithm

在我的2D物理模擬(Java)中,我按如下方法計算凸多邊形的中心,其中參數區域是之前計算的多邊形的封閉區域。

private Vector2d calculateCenterOfMass(double area) {
    Vector2d center = new Vector2d(0, 0);

    for (int i = 0; i < vertices.length; i++) {
        int j = (i + 1) % vertices.length;
        double factor = (vertices[i].x * vertices[j].y
                       - vertices[j].x * vertices[i].y);
        center.x += (vertices[i].x + vertices[j].x) * factor;
        center.y += (vertices[i].y + vertices[j].y) * factor;
    }
    center.scale(1 / (area * 6));

    return center;
}

我還具有一個具有以下幾點的多邊形,我使用該函數來計算其質心:

Vector2d [x=325.20399446366355, y=400.0, length=515.5168649182318]
Vector2d [x=375.20399446366355, y=400.0, length=548.4323453822622]
Vector2d [x=375.20399446366355, y=450.0, length=585.8993407245727]
Vector2d [x=325.20399446366355, y=450.0, length=555.2095442399406]

如您所見,僅通過查看y值即可知道中心必須在y = 425.0處 由於浮點魔術,y值改為425.00000000000017 作為參數給出的面積具有精確值2500.0

如何避免這種情況並獲得預期的425.0?

BigDecimal可以提供幫助,但我建議您閱讀整個答案。

從某種意義上講,浮點錯誤是“正常的”,即您不能將每個精確的浮點數存儲在變量中。 有很多資源可以解決這個問題,這里有一些鏈接:

  1. 如果您不知道實際的問題是什么,請查看此內容
  2. 每個計算機科學家應該了解的浮點運算法則
  3. IEEE浮點數
  4. 讓您了解如何工作: 數量模式

使用Double計算並存儲Long。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM