简体   繁体   English

避免算法中的浮点精度错误

[英]Avoid floating-point precision error in algorithm

In my 2D physics simulation (Java) I calculate the center of a convex polygon as follows, where the parameter area is the enclosed area of the polygon calculated before. 在我的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;
}

I further have a polygon with the following points I use the function to calculate the center of mass of: 我还具有一个具有以下几点的多边形,我使用该函数来计算其质心:

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]

As you can see just by looking at the y values the center must be at y=425.0 . 如您所见,仅通过查看y值即可知道中心必须在y = 425.0处 Due to floating point magic the y value becomes 425.00000000000017 instead. 由于浮点魔术,y值改为425.00000000000017 The area given as parameter has the exact value 2500.0 . 作为参数给出的面积具有精确值2500.0

How can I avoid this and get my expected 425.0? 如何避免这种情况并获得预期的425.0?

BigDecimal could help, but I would suggest reading the whole answer. BigDecimal可以提供帮助,但我建议您阅读整个答案。

Floating point errors are 'normal' in a sense, that you cannot store every floating point number exact within a variable. 从某种意义上讲,浮点错误是“正常的”,即您不能将每个精确的浮点数存储在变量中。 There are many resources out there how to deal with this problem, a few links here: 有很多资源可以解决这个问题,这里有一些链接:

  1. If you do not know what the actual problem is check this out. 如果您不知道实际的问题是什么,请查看此内容
  2. What Every Computer Scientist Should Know About Floating-Poit Arithmetic 每个计算机科学家应该了解的浮点运算法则
  3. IEEE floating point IEEE浮点数
  4. To give you an idead how to work: Quantity Pattern 让您了解如何工作: 数量模式

使用Double计算并存储Long。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM