Converting polygon coordinates from Double to Long for use with Clipper library

妖精的绣舞 提交于 2019-12-01 17:17:29

You can use a simple multiplier to convert between the two:

/* Using power-of-two because it is exactly representable and makes
the scaling operation (not the rounding!) lossless. The value 1024
preserves roughly three decimal digits. */
double const scale = 1024.0;

// representable range
double const min_value = std::numeric_limits<long>::min() / scale;
double const max_value = std::numeric_limits<long>::max() / scale;

long
to_long(double v)
{
    if(v < 0)
    {
        if(v < min_value)
            throw out_of_range();
        return static_cast<long>(v * scale - 0.5);
    }
    else
    {
        if(v > max_value)
            throw out_of_range();
        return static_cast<long>(v * scale + 0.5);
    }
}

Note that the larger you make the scale, the higher your precision will be, but it also lowers the range. Effectively, this converts a floating-point number into a fixed-point number.

Lastly, you should be able to locate code to compute intersections between line segments using floating-point math easily, so I wonder why you want to use exactly Clipper.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!