I'm trying to make something that would give me the slope and y-intercept from 2 points. Sometimes it would give me the correct values, but other times it would give me something close to correct but wrong.
Anyone know any thing that I could have done wrong? (Also, I feel like I should say that I'm just now starting to learn python)
y2 = input('Y2: ')
y1 = input('Y1: ')
x2 = input('X2: ')
x1 = input('X1: ')
y2 = float(y2)
y1 = float(y1)
x2 = float(x2)
x1 = float(x1)
over = y2-y1
under = x2-x1
m = over/under
y = float(y2)
x = float(x2)
m = float(m)
ym = y-m
b = ym/x
print(f'Y = {m}x {b}')
CodePudding user response:
it appears as though the mathematics for the intercept b
is incorrect.
it would be logical to use the x1, y1
coordinate with the slope to generate b
.
assume that you want to find x0, y0
where y0
= b
. Then you would do a similar calculation (already having calculated m
before as you correctly did).
So (y1-b) / x1 = m
. and you can just rearrange this to get:
b = y1 - m*x1
.
So this works:
x1, y1 = 1, 1
x2, y2 = 2, 2
over = y2-y1
under = x2-x1
m = over/under
b = y1 - m*x1
print(f'Y = {m}x {b}')
returns this:
Y = 1.0x 0.0