📜  两条平行线之间的距离

📅  最后修改于: 2021-04-22 04:17:49             🧑  作者: Mango

给定两条斜率为m的y截距分别为b1b2的平行直线。任务是找到这两条平行线之间的距离。
例子:

Input: m = 2, b1 = 4, b2 = 3
Output: 0.333333

Input: m = -4, b1 = 11, b2 = 23
Output: 0.8

方法

  1. PQRS为平行线,具有等式
    y = mx + b1
    y = mx + b2
  2. 这两条线之间的距离是这两条线与垂直线的两个交点之间的距离。让该距离为d
  3. 因此,垂直于PQRS的线的方程可以是
    y = -x / m
  4. 现在,分别用PQ和RS求解垂直线以获得相交点(x1,y1)(x2,y2) ,我们得到,
  5. PQ
    y = mx + b1
    y = -x / m
    (x1,y1)=(-b1 * m /(m ^ 2 +1),b1 /(m ^ 2 +1))
  6. RS
    y = mx + b2
    y = -x / m
    (x2,y2)=(-b2 * m /(m ^ 2 +1),b2 /(m ^ 2 +1))
  7. 因此, d =(x1,y1)与(x2,y2)之间的距离
    d = \frac{\left | b2 - b1 \right |}{ sqrt( m^{2} + 1 ) }

下面是上述方法的实现

C++
// C++ program find the distance
// between two parallel lines
 
#include 
using namespace std;
 
// Function to find the distance
// between parallel lines
double dist(double m, double b1, double b2)
{
    double d = fabs(b2 - b1) / ((m * m) - 1);
    return d;
}
 
// Driver Code
int main()
{
    double m = 2, b1 = 4, b2 = 3;
    cout << dist(m, b1, b2);
    return 0;
}


Java
// Java program find the distance
// between two parallel lines
class GFG
{
     
// Function to find the distance
// between parallel lines
static double dist(double m,
                double b1, double b2)
{
    double d = Math.abs(b2 - b1) /
                    ((m * m) - 1);
    return d;
}
 
// Driver Code
public static void main(String[] args)
{
    double m = 2, b1 = 4, b2 = 3;
     System.out.println(dist(m, b1, b2));
}
}
 
// This code is contributed by Code_Mech.


Python3
# Python3 program find the distance
# between two parallel lines
 
# Function to find the distance
# between parallel lines
def dist(m, b1, b2):
    d = abs(b2 - b1) / ((m * m) - 1);
    return d;
 
# Driver Code
def main():
    m, b1, b2 =2,4, 3;
    print(dist(m, b1, b2));
if __name__ == '__main__':
    main()
 
# This code contributed by PrinciRaj1992


C#
// C# program find the distance
// between two parallel lines
using System;
 
class GFG
{
     
// Function to find the distance
// between parallel lines
static double dist(double m,
                   double b1, double b2)
{
    double d = Math.Abs(b2 - b1) /
                      ((m * m) - 1);
    return d;
}
 
// Driver Code
public static void Main()
{
    double m = 2, b1 = 4, b2 = 3;
    Console.Write(dist(m, b1, b2));
}
}
 
// This code is contributed by Akanksha Rai


PHP


Javascript


输出:
0.333333