X和Y拦截斜坡 - Python

时间:2015-03-01 03:01:06

标签: python calculator

我一直在研究斜率计算器,它也可以找到x和y截取...我如何在Python中执行此操作?谢谢! 这是我目前的代码:

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

4 个答案:

答案 0 :(得分:2)

要找到y轴截距(b),你需要将x设置为其中一个x值,如果y值设置为y,则需要求解:

y=mx+b
b=y-mx

该功能可能如下所示:

m=getSlope(x1,y1,x2,y2)
b=y1-m*x1
return b

该点的坐标为(0,b),因此您可以根据需要返回该坐标。

答案 1 :(得分:2)

坡度:

from __future__ import division
def getSlope((x1, y1), (x2, y2)):
    return (y2-y1)/(x2-x1)

对于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))
7.810249675906654
>>> getYInt((7, 3), (2, 9))
(0, 11.4)
>>> 

答案 2 :(得分:0)

一行的公式是

y = m * x + c # m-->slope, c-->intercept
c = y - m * x # same formula rearranged.

getYInt函数中,您只需要以下这些行:

def getYInt(x1, y1, x2, y2):
    s = getSlope(x1, y1, x2, y2)
    return y1 - s * x1

另外,如果您使用的是Python 2系列,请注意整数除法。

答案 3 :(得分:0)

import sys

def test(did_pass):
    """  Print the result of a test.  """
    linenum = sys._getframe(1).f_lineno   # Get the caller's line number.
    if did_pass:
        msg = "Test at line {0} ok.".format(linenum)
    else:
        msg = ("Test at line {0} FAILED.".format(linenum))
    print(msg)


def slope(x1, y1, x2, y2):
    return (y2-y1)/(x2-x1)

test(slope(5, 3, 4, 2) == 1.0)  # ok
test(slope(1, 2, 3, 2) == 0.0)  # ok
test(slope(1, 2, 3, 3) == 0.5)  # ok
test(slope(2, 4, 1, 2) == 2.0)  # ok

def intercept(x1, y1, x2, y2):   # y1 = mx1 + q -> q = y1 - mx1
    m = slope(x1, y1, x2, y2)
    q = y1 - m * x1
    return q

test(intercept(1, 6, 3, 12) == 3.0)  # ok
test(intercept(6, 1, 1, 6) == 7.0)   # ok
test(intercept(4, 6, 12, 8) == 5.0)  # ok
相关问题