X and Y Intercepts From Slopes - Python
Solution 1
To find the y-intercept (b), you need to set x to one of the x values and y to one if the y values and solve:
y=mx+b
b=y-mx
The function could look like this:
m=getSlope(x1,y1,x2,y2)
b=y1-m*x1
return b
The coordinates of the point would be (0,b)
, so you can return that instead if you want.
Solution 2
For slope:
from __future__ import division
def getSlope((x1, y1), (x2, y2)):
return (y2-y1)/(x2-x1)
For y-intercept
def getYInt((x1, y1), (x2, y2)):
slope = getSlope((x1, y1), (x2, y2))
y = -x1*slope+y1
return (0, y)
>>> slope((7, 3), (2, 9))
-1.2
>>> getYInt((7, 3), (2, 9))
(0, 11.4)
>>>
Captain Cucumber
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ # &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ *******************************************************************************************###########################################################################################@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ *******************************************************************************************###########################################################################################@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ *******************************************************************************************###########################################################################################
Updated on June 19, 2022Comments
-
Captain Cucumber almost 2 years
I have been working on a slope calculator that also finds x and y intercepts... how do I do this in Python? Thanks! Here is my current code:
def getSlope(x1, y1, x2, y2): slope = (y2-y1)/(x2-x1) return slope def getYInt(x1, y1, x2, y2): s = getSlope(x1, y1, x2, y2) x = 0 y = s*0 + yi
-
KSFT about 9 yearsThis is almost exactly the same as the other two answers.
-
Haleemur Ali about 9 yearsyeah @KSFT. I think we all submitted our answers at around the same time, and as far as I'm aware, there's only one straightforward way to get the slope / intercept of a line.
-
Alessandro Anderson over 6 yearsDon't bother about the first function it is just to check if the other two are correct. Namasté