我有以下代码...

public class Point {
    private double x;
    private double y;
    static private final double RADTODEG = 180.0d / Math.PI ;
    static private final double DEGTORAD = Math.PI / 180.0d;

    /**
     * Rotates the point by a specific number of radians about a specific origin point.
     * @param origin The origin point about which to rotate the point
     * @param degrees The number of radians to rotate the point
     */
    public void rotateByRadians(Point origin, double radians) {
        double cosVal = Math.cos(radians);
        double sinVal = Math.sin(radians);

        double ox = x - origin.x;
        double oy = y - origin.y;

        x = origin.x + ox * cosVal - oy * sinVal;
        y = origin.y + ox * sinVal + oy * cosVal;
    }

    /**
     * Rotates the point by a specific number of degrees about a specific origin point.
     * @param origin The origin point about which to rotate the point
     * @param degrees The number of degrees to rotate the point
     */
    public void rotateByDegrees(Point origin, double degrees) {
        rotateByRadians(origin, degrees * DEGTORAD);
    }

    /**
     * Rotates the point by the specified number of radians about the axis' origin (0,0). To rotate about a specific origin point, see rotateByRadians(Point, double)
     * @param radians Measure of radians to rotate the point
     */
    public void rotateByRadians(double radians) {
        if(isEmpty()) // Since we're rotating about 0,0, if the point is 0,0, don't do anything
            return;

        double cosVal = Math.cos(radians);
        double sinVal = Math.sin(radians);

        double newx = x * cosVal - y * sinVal;
        double newy = x * sinVal + y * cosVal;

        x = newx;
        y = newy;
    }

    /**
     * Rotates the point by the specified number of degrees about to the axis' origin (0,0). To rotate about a specific origin point, see rotateByDegrees(Point, double)
     * @param degrees Measure of degrees to rotate the point
     */
    public void rotateByDegrees(double degrees) {
        rotateByRadians(degrees * DEGTORAD);
    }


给定一个点(例如0,200)会出现问题。将旋转角度(绕轴原点0,0旋转)180度应为(0,-200)。 x坐标不应更改。但是,它最终是(-2.4492935982947064E-14,-200)。我尝试使用strictfp,但没有任何区别。仅当旋转的坐标为零时,这才影响结果。非零值可以正常工作。任何想法,为什么这是不正确的?

代码如下:

   Point p = new Point(0.0d, 200.0d);
   p.rotateByDegrees(180.0d);
   System.out.println(p);


给出输出:

shapelib.Point Object {x: -2.4492935982947064E-14 y: -200.0}

最佳答案

浮点运算不是完全准确的。在大多数情况下,10 ^ -14幂的误差就足够了。
如果计算Math.sin(Math.PI),将得到1.2246467991473532E-16。为什么您需要精确地获得0?

10-07 19:51
查看更多