Given are two parallel straight lines with slope m, and different y-intercepts b1 & b2.The task is to find the distance between these two parallel lines.
Examples:
Input: m = 2, b1 = 4, b2 = 3
Output: 0.333333
Input: m = -4, b1 = 11, b2 = 23
Output: 0.8

Approach:
- Let PQ and RS be the parallel lines, with equations
y = mx + b1
y = mx + b2
- The distance between these two lines is the distance between the two intersection points of these lines with the perpendicular line.Let that distance be d.
- So, equation of the line perpendicular to PQ and RS can be
y = -x/m
- Now, solving the perpendicular line with PQ and RS separately to get the intersecting points (x1, y1) & (x2, y2), we get,
- From PQ,
y = mx + b1
y = -x/m
(x1, y1) = ( -b1*m/(m^2 + 1), b1/(m^2 + 1))
- From RS,
y = mx + b2
y = -x/m
(x2, y2) = ( -b2*m/(m^2 + 1), b2/(m^2 + 1))
- So, d = distance between (x1, y1) and (x2, y2)

Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
double dist(double m, double b1, double b2)
{
double d = fabs(b2 - b1) / ((m * m) - 1);
return d;
}
int main()
{
double m = 2, b1 = 4, b2 = 3;
cout << dist(m, b1, b2);
return 0;
}
|
Java
class GFG
{
static double dist(double m,
double b1, double b2)
{
double d = Math.abs(b2 - b1) /
((m * m) - 1);
return d;
}
public static void main(String[] args)
{
double m = 2, b1 = 4, b2 = 3;
System.out.println(dist(m, b1, b2));
}
}
|
Python3
def dist(m, b1, b2):
d = abs(b2 - b1) / ((m * m) - 1);
return d;
def main():
m, b1, b2 =2,4, 3;
print(dist(m, b1, b2));
if __name__ == '__main__':
main()
|
C#
using System;
class GFG
{
static double dist(double m,
double b1, double b2)
{
double d = Math.Abs(b2 - b1) /
((m * m) - 1);
return d;
}
public static void Main()
{
double m = 2, b1 = 4, b2 = 3;
Console.Write(dist(m, b1, b2));
}
}
|
PHP
<?php
function dist($m, $b1, $b2)
{
$d = abs($b2 - $b1) / (($m * $m) - 1);
return $d;
}
$m = 2;
$b1 = 4;
$b2 = 3;
echo dist($m, $b1, $b2);
?>
|
Javascript
<script>
function dist(m, b1 , b2)
{
var d = Math.abs(b2 - b1) /
((m * m) - 1);
return d;
}
var m = 2, b1 = 4, b2 = 3;
document.write(dist(m, b1, b2).toFixed(5));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
07 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...