【问题标题】:python midpoint line clipping algorithmpython中点线裁剪算法
【发布时间】:2014-03-28 21:29:13
【问题描述】:

python(2.7) 中的这个中点算法不起作用。他并没有退出递归。错误在哪里?请帮帮我。

# Where is point
def vcode(rect, p):
    value = 0
    if p.x < rect.x_min:
        value += LEFT
    if p.x >= rect.x_max:
        value += RIGHT
    if p.y < rect.y_min:
        value += BOT
    if p.y >= rect.y_max:
        value += TOP

    return value

# algorithm
def average_point(rect, p1, p2, count=0):
    code_a = vcode(rect, p1)
    code_b = vcode(rect, p2)
    if math.sqrt((p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y)) < EPS:
        return
    if not (code_a | code_b):
        return
    if code_a & code_b:
        return
    mid = Point((p2.x+p1.x)/2.0, (p2.y+p1.y)/2.0)
    count += 1
    average_point(rect, p1, mid, count)
    mid.x = mid.x+1
    mid.y = mid.y+1
    average_point(rect, mid, p2, count)
    return count


p1, p2 是Point( class, fields(x, y));

rect 是Rectangle( class, fields(x_min, y_min, x_max, y_max));

【问题讨论】:

    标签: python algorithm graphics geometry


    【解决方案1】:

    您的代码工作正常,除了它在第一次调用该方法时返回 count 的最终值。因此,count 将始终为 1。要更正此问题,您需要将 count 设置为 average_point 的返回值。然后,您的代码将如下所示:

    # algorithm
    def average_point(rect, p1, p2, count=0):
        returnArray = []
        code_a = vcode(rect, p1)
        code_b = vcode(rect, p2)
        if math.sqrt((p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y)) < EPS:
            returnArray.append(count)
            returnArray.append(p1)
            returnArray.append(p2)
            return returnArray
        if not (code_a | code_b):
            returnArray.append(count)
            returnArray.append(p1)
            returnArray.append(p2)
            return returnArray
        if code_a & code_b:
            returnArray.append(count)
            returnArray.append(p1)
            returnArray.append(p2)
            return returnArray
        mid = Point((p2.x+p1.x)/2.0, (p2.y+p1.y)/2.0)
        count += 1
        returnArray = average_point(rect, p1, mid, count)
        mid.x = mid.x+1
        mid.y = mid.y+1
        returnArray = average_point(rect, mid, p2, count)
        return returnArray
    

    这将在每次迭代时替换 count 值,并且确保添加 return counts,否则它将无法接收到正确的值。

    这还包括索引 1 和 2 中的点,因为在 python 中,您可以在数组中有多个“类型”,因此您可以返回点和计数。

    【讨论】:

    • 他其实有三个条件可以跳出递归。但显然没有遇到过。
    • @Hyperboreus 啊真的……错过了
    • @Wolkodav EPS 的值是多少?
    • 价值不大。每股收益=1。我比较了线的长度和最小的线。
    • 任务是:区间划分多少次,算法。然后我最常将这个结果与其他结果进行比较。但有时这个函数并没有退出递归,我得到的“count”总是等于 1(
    猜你喜欢
    • 2016-03-10
    • 2011-05-20
    • 1970-01-01
    • 2012-03-14
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 2014-10-10
    相关资源
    最近更新 更多