Skip to content
Advertisement

Php code to see if two lines are parallel

I want to write a PHP code to see if two lines are parallel.

We have

The four points are P(x1, y1), Q(x2, y2), R(x3, y3), S(x4, y4)



<?php
 fscanf(STDIN, '%d', $n); 
for ($i = 0; $i < $n; $i++) {
    fscanf(STDIN, '%f %f %f %f %f %f %f %f', $x1, $y1, $x2, $y2, $x3, $y3, $x4, $y4);
    $pq = INF;
    if ($x2 - $x1 !== 0.0) {
        $pq = ($y1 - $y2) / ($x1 - $y1);
    }
    $rs = INF;
    if ($x4 - $x3 !== 0.0) {
        $rs = ($x4 - $x3) / ($x3 - $y4);
    } 
    echo $pq === $rs ? 'PQ and RS are parallel.' : 'PQ and RS are not parallel.';
    echo PHP_EOL;
}
?>

But it’s not working correct even if given two parallel lines

Advertisement

Answer

The Slope is equal to m = (y2 - y1) / (x2 - x1)

I made some changes in your formula so it’s working I think.

<?php
 fscanf(STDIN, '%d', $n); 
for ($i = 0; $i < $n; $i++) {
    fscanf(STDIN, '%f %f %f %f %f %f %f %f', $x1, $y1, $x2, $y2, $x3, $y3, $x4, $y4);
    $pq = INF;
    if ($x2 - $x1 !== 0.0) {
        $pq = ($y2 - $y1) / ($x2 - $x1);
    }
    $rs = INF;
    if ($x4 - $x3 !== 0.0) {
        $rs = ($y4 - $y3) / ($x4 - $x3);
    } 
    echo $pq === $rs ? 'PQ and RS are parallel.' : 'PQ and RS are not parallel.';
    echo PHP_EOL;
}
?>

it’s just a math problem

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement