在Python中计算给定斜率的y截距

0 投票
3 回答
4188 浏览
提问于 2025-04-17 09:03

我正在尝试计算一个斜率的截距,但我所有的测试单元都无法正常工作。我能让第一个测试单元正常运行,但最后一个我遇到了一些问题。有人能帮我找出错误吗?

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

这看起来像是作业。试着手动计算一下最后的测试案例,并把结果打印出来,看看你得到的值是否一样。

比如:把你的斜率函数换成下面这个

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
2

你传入的是整数值,所以 '/' 这个运算符默认进行整数除法。只需要改变一下 slope 的值就可以了:

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

    m = (y2/x2)
    return m
4

你可以从测试输出中得到一个提示:期望值是 '5.0',但实际得到的是 '8'。 注意,期望值是一个浮点数,而实际结果是一个整数。

一个简单的解决办法是把你的 slope 函数改成:

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

    m = (1.0*y2/x2)
    return m

另一种解决方法是切换到 Python 3,或者在你的 .py 文件顶部添加 from __future__ import division。在 Python 3 中,除法默认会得到浮点数。想了解更多,可以查看 PEP 238 的详细讨论。

撰写回答