Inconsistent result for lab in Python course: m/10 vs m*0.1

Hi Guys,
I’m a bit frustrated about results I’m getting while doing lab at the end of chapter 5
Could someone guide me why m/10 vs m*0.1 is not equivalent?

Steps to reporoduce:

def get_y(m, b, x):
  y = m*x + b
  return y

def calculate_error(m, b, point):
  x_point, y_point = point
  y = m*x_point + b
  distance = abs(y - y_point)
  return distance

def calculate_all_error(m, b, points):
    total_error = 0
    for point in datapoints:
        point_error = calculate_error(m, b, point)
        total_error += point_error
    return total_error

datapoints = [(1, 2), (2, 0), (3, 4), (4, 4), (5, 3)]

possible_ms = [m*0.1 for m in range(-100,101,1)]
possible_bs = [b*0.1 for b in range(-200,201,1)]

error = 0
best_m = 0
best_b = 0

smallest_error = (float("inf"))

for m in possible_ms:
    for b in possible_bs:
        error = calculate_all_error(m,b,datapoints) 
        if error < smallest_error:
            smallest_error = error
            best_m = m
            best_b = b

print(best_m,best_b,smallest_error)
"""
possible_ms = [m/10 for m in range(-100,101,1)]
possible_bs = [b/10 for b in range(-200,201,1)]
0.4 1.6 5.0

possible_ms = [m*0.1 for m in range(-100,101,1)]
possible_bs = [b*0.1 for b in range(-200,201,1)]
0.30000000000000004 1.7000000000000002 4.999999999999999

"""

Link to similar question

Thanks a lot for getting back. I really enjoyed learning things in codeacademy.
And the forum is great. I didn’t expect for someone to answer :slight_smile:
but
I guess question in that thread is slightly different to mine. In that post author concerned by getting 0.3 by 3/10 and getting 0.300000000000004 when 3*01.

My question is slightly different:
I’m getting completely wrong result for my coefficients in lab:

possible_ms = [m/10 for m in range(-100,101,1)]
possible_bs = [b/10 for b in range(-200,201,1)]
0.4 1.6 5.0

possible_ms = [m*0.1 for m in range(-100,101,1)]
possible_bs = [b*0.1 for b in range(-200,201,1)]
0.30000000000000004 1.7000000000000002 4.999999999999999

I’m really struggle to debug why I’m getting
0.4 1.6 5.0
and
0.30000000000000004 1.7000000000000002 4.999999999999999

I would accept 0.40000000000000004 but not 0.30000000000000004

Please help.

You’re not getting a completely different result, you’re getting an approximately equivalent result.

You have to keep in mind what it is you’re doing. You’re looking for some set of values resulting in the smallest error.

For them to be completely different you would need to calculate the error and show that those errors are completely different. You’d have to show that you’re no longer getting a set of values that produces that smallest amount of error.

1 Like