Page 1 of 1

square root

Posted: 26 Aug 2009 09:33
by Kogut
How to get square root of sth? ( AITile.GetDistanceSquareToTile(...))

Re: square root

Posted: 26 Aug 2009 09:53
by SmatZ
Functions like this aren't provided for performance reasons.
Either use AITile::GetDistanceManhattanToTile(), or work with squared distances.

Re: square root

Posted: 26 Aug 2009 09:56
by Kogut
When I get money (distanse * sth_depending_on_cargo_and_time_of_travel ), distance is manhattan distance or "normal" distance?

Re: square root

Posted: 26 Aug 2009 10:00
by Zutty
This will probably come with the AI common library...

Code: Select all

/*
 * Square root using Newton-Raphson method.
 */
::sqrtlut <- [0, 10, 100, 1000, 10000, 100000, 1000000, 10000000];
function sqrt(d) {
    if (d == 0.0) {
    	return 0.0;
    }
    
    local nd = 0;
    for(nd = 7; nd >= 0; nd--) {
    	if(nd <= ::sqrtlut[nd]) break;
    }
    nd++;
    local x = pow(2.0, nd);
    
    for(local i = 0; i < 5; i++) {
    	x = x - (x*x - d) / (2*x);
    }
    
	return x;
}

/*
 * Raises num to the power p.
 */
function pow(num, p) {
	return (p <= 0) ? 1 : num * pow(num, p - 1);
}
Its pretty slow (compared to just getting the manhattan distance) so only use it when you really need to.

Edit: Oh and pow() is just raise to the power.

Re: square root

Posted: 26 Aug 2009 10:05
by Zutty
Kogut wrote:When I get money (distanse * sth_depending_on_cargo_and_time_of_travel ), distance is manhattan distance or "normal" distance?
Ah! You need manhattan distance. In OpenTTD euclidean distance (i.e. sqrt of square distance) will give an underestimate becuase of the way the map works.

Only use euclidean distance when you want some kind of pseudo-circular pattern. I use it for creating rings of trees around towns.

Edit: Sorry for double post.