I'm working on the exercises from Chapter 5 of How to Think Like a Computer Scientist, and am trying to solve the 3rd exercise:
Write a function
slope(x1, y1, x2, y2)
that returns the slope of the line through the points (x1, y1) and (x2, y2). Be sure your implementation ofslope
can pass the following doctests:def slope(x1, y1, x2, y2): """ >>> slope(5, 3, 4, 2) 1.0 >>> slope(1, 2, 3, 2) 0.0 >>> slope(1, 2, 3, 3) 0.5 >>> slope(2, 4, 1, 2) 2.0 """
This is the code I've come up with:
def slope(x1, y1, x2, y2):
"""
>>> slope(5, 3, 4, 2)
1.0
>>> slope(1, 2, 3, 2)
0.0
"""
sy = float(y1 - y2)
sx = float(x1 - x2)
return sy / sx
On the 2nd doctest I'm getting -0.0
instead of 0.0
… which is confusing, since I didn't know -0.0
was a thing. I know I can use abs()
to get the absolute value but, then if I do have parameters that should come out to a negative number, it won't work.
Also know I can set a condition on the result so it uses the absolute value or doesn't, but I'm wondering if I'm just doing something wrong here.