Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this PHP function return the wrong result?

Tags:

php

I wrote a user function to return the distance between two points on an x,y coordinate system. The input params were 0,0,10,10.

Here is the original code:

public static function dist2d($x1,$y1,$x2,$y2) {
   return sqrt((($x2 - $x1) * ($x2 - $x1)) + (($y2 - $y1) * ($y2 - $y1)));
}

This returns 110.

Here is the code that works:

public static function dist2d($x1,$y1,$x2,$y2) {
    $result = (($x2 - $x1) * ($x2 - $x1)) + (($y2 - $y1) * ($y2 - $y1));
    return sqrt($result);
}

This returns 14.1.

I am new to PHP, what is going on here?

like image 425
Mel Avatar asked Mar 18 '26 21:03

Mel


1 Answers

Both of these functions return 14.142135623731.

like image 59
Dan Grossman Avatar answered Mar 20 '26 10:03

Dan Grossman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!