Re: Calculation error - PHP not following math hierarchi ???

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

 



See

http://us3.php.net/manual/en/language.operators.php
http://us3.php.net/manual/en/language.operators.bitwise.php


You want this:

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(pow( $distX,2) + pow($distY,2));
 } elseif ($distX > 150 && $distY <= 150) {
   $dist = sqrt(pow((abs(300 - $newX)),2) + pow($distY,2));
 } elseif ($distX <= 150 && $distY > 150) {
   $dist = sqrt(pow($distX,2) + pow((abs(300 - $newY)),2));
 } else {
   $dist = sqrt(pow((abs(300 - $newX)),2) + pow((abs(300 - $newY)),2));
 }

 return $dist;
}

echo calc_distance( 150, 150, 300, 300 );  //echoes 212.13203435596
echo "<br>150^2=".(150^2)." and pow(150,2)=".(pow(150,2)); //echoes 150^2=148 and pow(150,2)=22500




kgt




Rene Brehmer wrote:

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

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