When you do this:
m = (y1-y2) / (x1-x2)
You get a float (a floating point representation of a real number), not an int (an integer).
Then, because m
is a float, b
too is a float. Then, when you call str
on a float, you get a decimal point.
The right way to fix this depends on what you actually want to do.
If you really want to deal only with integers, you can use integer division:
m = (y1-y2) // (x1-x2)
That means if, say, x1, x2, y1, y2 = 4, 2, 2, 1
you'll end up with b = 2
(2 - 0 * 4
). I suspect that isn't what you want; you actually want to multiply that 4
by 1/2
, and then round the result afterward.
In that case, you can do the conversion the same place you round:
m = int(round(m, 0))
b = int(round(b, 0))
Note that your existing calls to round
didn't actually do anything; round(m, 0)
doesn't modify m
, it returns a new value that's the rounded version of m
, which you have to assign back to m
(or somewhere else).
One more thing to consider: You probably really do want literally one half, not "the closest floating point representation to 0.5".
You probably don't actually care about the difference—unless you're using quite large integers, the rounding errors won't ever be visible. But if you do care, you may want to consider using a third-party exact-fraction module (e.g., clnum
), or possibly the standard library decimal
. This would mean you have to be more explicit, so I wouldn't do this unless you expect it to be necessary. But if it is necessary, it would look something like this:
m = decimal.Decimal(y1-y2) / (x1-x2)
b = y1 - m * x1
m = int(m.to_integral(rounding=decimal.ROUND_HALF_UP))
b = int(b.to_integral(rounding=decimal.ROUND_HALF_UP))
Finally, you can always keep the numbers around as float
s (or Decimal
s, etc.), never rounding or converting them, and force them to print as integers anyway:
print("Y = {:.0g}X - {:.0g}.".format(m, b))
'{:g}'
and'{:.0g}'
, because I think the latter may be what he actually wants. (It's also worth pointing out that he's already trying to round his numbers to the nearest integer, but it's not working.) – Testee