在python中找出具有给定斜率的y-intercept

时间:2011-12-27 01:08:17

标签: python math geometry

我正在尝试计算斜率的截距,但我不能将所有测试单位都工作。我得到第一个测试单元,但最后一个我遇到了麻烦。有人可以帮我找到错误吗?

def test(actual, expected):
    """ Compare the actual to the expected value,
        and print a suitable message.
    """
    import sys
    linenum = sys._getframe(1).f_lineno   # get the caller's line number.
    if (expected == actual):
        msg = "Test on line {0} passed.".format(linenum)
    else:
        msg = ("Test on line {0} failed. Expected '{1}', but got '{2}'."
                                 . format(linenum, expected, actual))
    print(msg)

def slope (x1, y1, x2, y2):
    x2 = (x2 - x1)
    y2 = (y2 - y1)

    m = (y2/x2)
    return m

def intercept(x1, y1, x2, y2):
    m = slope(x1,y1,x2,y2)
    b = y2 - (m*x2)
    return b 


def test_suite():
    test(intercept(1, 6, 3, 12), 3.0)
    test(intercept(6, 1, 1, 6), 7.0)
    test(intercept(4, 6, 12, 8), 5.0)






test_suite()

3 个答案:

答案 0 :(得分:4)

您将通过测试输出获得线索:Expected '5.0', but got '8'.请注意,期望值是浮点数,但实际结果是整数。

快速解决方法是将slope功能更改为:

def slope (x1, y1, x2, y2):
    x2 = (x2 - x1)
    y2 = (y2 - y1)

    m = (1.0*y2/x2)
    return m

另一种解决方法是切换到Python 3,或将from __future__ import division添加到.py文件的顶部。在Python 3中,默认情况下,除法转换为浮点。有关更详细的讨论,请参阅PEP 238

答案 1 :(得分:2)

您传递的是整数值,因此'/'运算符默认为整数除法。更改slope足够:

def slope (x1, y1, x2, y2):
    x2 = float(x2 - x1)
    y2 = float(y2 - y1)

    m = (y2/x2)
    return m

答案 2 :(得分:0)

看起来像我的作业。尝试手动浏览最终的测试用例并打印出值,看看是否得到相同的结果。

例如:用以下

替换您的斜率函数
def slope (x1, y1, x2, y2):
    x2 = (x2 - x1)
    y2 = (y2 - y1)
    print y2,x2
    m = (y2/x2)
    print m
    print 1.0*y2/x2
    return 1.0*y2/x2