Reply to Calculation error - PHP not following math hierarchi ???

Your name:

Reply:


Posted by Rene Brehmer on 08/03/05 17:42

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...

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация