Calculation error - PHP not following math hierarchi ???

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I've run into a situation where PHP is way off when doing a relatively
simple calculation of distance between two points in 2-dimensional space,
where coordinates go from 1 to 300 in both X and Y directions. When passing
300, it goes back to 1, and vise-versa (it's for a game and is supposed to
approximate the movement over a sphere).

Using this function:

function calc_distance($curX,$curY,$newX,$newY) {
  // calculate distance to new location
  $distX = abs($curX - $newX);
  $distY = abs($curY - $newY);
  
  if ($distX <= 150 && $distY <= 150) {
    $dist = sqrt($distX^2 + $distY^2);
  } elseif ($distX > 150 && $distY <= 150) {
    $dist = sqrt((abs(300 - $newX))^2 + $distY^2);
  } elseif ($distX <= 150 && $distY > 150) {
    $dist = sqrt($distX^2 + (abs(300 - $newY))^2);
  } else {
    $dist = sqrt((abs(300 - $newX))^2 + (abs(300 - $newY))^2);
  }
  
  return $dist;
}

And using 150,150 as $curX,$curY and 300,300 as $newX,$newY ... PHP
calculates $dist as 3.46410161514
which obviously is far off target ...referring to my calcultor, the correct
result for the same code is supposed to be 212.1320

What happens here ? And how the heck do I get to calculate right ?

Float errors usually isn't this severe, so I'm assuming it's a problem with
properly acknowledging the hierarchi of the mathematical operators ... 

It's PHP ver. 4.3.0, on Apache/2.0.53 (Win32), on WinXP SP1

I've been trying to manually calculate the formula out of order to figure
out how the strange result comes about, but haven't had any success yet ... 

Any suggestions ?

Rene
-- 
Rene Brehmer
aka Metalbunny

We have nothing to fear from free speech and free information on the
Internet, but pop-up advertising! 

http://metalbunny.net/
My little mess of things...

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux