将多边形坐标从Double转换为Long,用于Clipper库 [英] Converting polygon coordinates from Double to Long for use with Clipper library

查看:572
本文介绍了将多边形坐标从Double转换为Long,用于Clipper库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个多边形,其顶点存储为双坐标。我想找到这些多边形的交叉区域,所以我在查看 Clipper库(C ++版本)。问题是,Clipper只能使用整数数学(它使用Long类型)。

I have two polygons with their vertices stored as Double coordinates. I'd like to find the intersecting area of these polygons, so I'm looking at the Clipper library (C++ version). The problem is, Clipper only works with integer math (it uses the Long type).

有没有办法,我可以安全地转换我的多边形与相同的比例因子,将其坐标转换为长,使用Clipper执行交叉算法,并缩放结果的交集用相同的因子返回多边形,并将其转换回双精度,而不会有太多的精度损失?

Is there a way I can safely transform both my polygons with the same scale factor, convert their coordinates to Longs, perform the Intersection algorithm with Clipper, and scale the resulting intersection polygon back down with the same factor, and convert it back to a Double without too much loss of precision?

我不能让我的头脑如何做。

I can't quite get my head around how to do that.

推荐答案

您可以使用简单的乘法器在两者之​​间进行转换:

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.

最后,你应该能够定位代码来计算线段之间的交点使用浮点数学很容易,所以我想知道你为什么要使用正确的Clipper。

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.

这篇关于将多边形坐标从Double转换为Long,用于Clipper库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆