【问题标题】:X and Y Intercepts From Slopes - Python斜坡的 X 和 Y 截距 - Python
【发布时间】:2015-03-01 03:01:06
【问题描述】:

我一直在研究一个斜率计算器,它还可以找到 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

【问题讨论】:

  • 记忆中应该是return s * -x1 + y1

标签: python calculator


【解决方案1】:

要找到 y 截距 (b),您需要将 x 设置为 x 值之一,如果 y 值设置为 1 并求解:

y=mx+b
b=y-mx

函数可能如下所示:

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

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

【讨论】:

    【解决方案2】:

    对于坡度:

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

    对于 y 截距

    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)
    >>> 
    

    【讨论】:

      【解决方案3】:

      线的公式是

      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 系列,请注意整数除法。

      【讨论】:

      • 这和其他两个答案几乎一模一样。
      • 是的@KSFT。我想我们几乎都在同一时间提交了答案,据我所知,只有一种直接的方法可以获得直线的斜率/截距。
      【解决方案4】:
      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
      

      【讨论】:

      • 不要在意第一个函数,它只是检查其他两个是否正确。合十礼
      猜你喜欢
      • 1970-01-01
      • 2017-09-13
      • 2018-02-28
      • 2018-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-15
      相关资源
      最近更新 更多