用python计算给定斜率的y截距
我试图计算一个斜率的截距,但我不能让所有的测试单元都工作。我让第一个测试单元开始工作,但最后一个我遇到了一些麻烦。有人能帮我找到错误吗用python计算给定斜率的y截距,python,math,geometry,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 #
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()
您正在传递整数值,因此“/”运算符默认为整数除法。更改
坡度
即可:
def slope (x1, y1, x2, y2):
x2 = float(x2 - x1)
y2 = float(y2 - y1)
m = (y2/x2)
return m
您正在传递整数值,因此“/”运算符默认为整数除法。更改
坡度
即可:
def slope (x1, y1, x2, y2):
x2 = float(x2 - x1)
y2 = float(y2 - y1)
m = (y2/x2)
return m
对我来说像是家庭作业。试着手工完成最终的测试用例并打印出值,看看是否得到相同的结果 e、 g:将坡度功能替换为以下功能
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
对我来说像是家庭作业。试着手工完成最终的测试用例并打印出值,看看是否得到相同的结果 e、 g:将坡度功能替换为以下功能
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
测试输出为您提供了一条线索:
预期为“5.0”,但得到了“8”。
请注意,预期值是一个浮点数,但实际结果是一个整数
快速修复方法是将坡度功能更改为:
def slope (x1, y1, x2, y2):
x2 = (x2 - x1)
y2 = (y2 - y1)
m = (1.0*y2/x2)
return m
另一个修复方法是切换到Python3,或者将从uuuu future\uuuuu import division添加到.py文件的顶部。在Python3中,除法在默认情况下强制转换为浮点。有关更详细的讨论,请参阅。测试输出为您提供了一条线索:预期为“5.0”,但得到了“8”。
请注意,预期值是一个浮点数,但实际结果是一个整数
快速修复方法是将坡度功能更改为:
def slope (x1, y1, x2, y2):
x2 = (x2 - x1)
y2 = (y2 - y1)
m = (1.0*y2/x2)
return m
另一个修复方法是切换到Python3,或者将从uuuu future\uuuuu import division添加到.py文件的顶部。在Python3中,除法在默认情况下强制转换为浮点。有关更详细的讨论,请参阅。谢谢!我不知道我必须加一个“.0”才能成为浮点数。谢谢!我不知道必须输入“.0”才能使其成为浮点数。另请参见:另请参见: