[Tutor] Expecting a float but get an int

Chris Roy-Smith chris_roysmith at internode.on.net
Sun May 23 04:22:30 EDT 2021


On 23/5/21 5:28 pm, Phil wrote:
> Help please.
> 
> This function returns "a" as .7 and "b" as 0 instead of .7. I'm sure the 
> reason is obvious but I cannot see what it is.
> 
> def slope_intercept(x1, x2, y1, y2):
>      a = (y2 - y1) / (x2 - x1) # a = .7 which is correct
>      #a = .7
> 
>      b = (y1 - (a * x1) # b = 0 where it should be .7
>      return a, b
> 
> slope, intercept = slope_intercept(9, 0, 7, 0)
> print("slope :", slope, "intercept :", intercept)
> 
> This is what I've tried:
> 
>      a = float((y2 - y1) / (x2 - x1))
> 
>      b = float((y1 - (a * x1))
> 
> In the function:
> 
> x1 = float(x1)
> 
> the same for x2, y1, y2
> 
> The debugger show "a" and "b" to be floats.
> 
> The only way that I can have "b" show the correct answer is if I 
> specifically make a = .7.
> 
> What have I overlooked?
> 
Hi,
try making the values for x1, x2, y1, y2 floats before calling the 
function. Python does integer math on integers. even making one value in 
each calculation a float will make python to do floating point math.

regards,
Chris


More information about the Tutor mailing list