square root

Discuss the new AI features ("NoAI") introduced into OpenTTD 0.7, allowing you to implement custom AIs, and the new Game Scripts available in OpenTTD 1.2 and higher.

Moderator: OpenTTD Developers

Post Reply
Kogut
Tycoon
Tycoon
Posts: 2493
Joined: 26 Aug 2009 06:33
Location: Poland

square root

Post by Kogut »

How to get square root of sth? ( AITile.GetDistanceSquareToTile(...))
Correct me If I am wrong - PM me if my English is bad
AIAI - AI for OpenTTD
SmatZ
OpenTTD Developer
OpenTTD Developer
Posts: 351
Joined: 03 Oct 2006 18:26
Location: Prague, Czech Republic
Contact:

Re: square root

Post by SmatZ »

Functions like this aren't provided for performance reasons.
Either use AITile::GetDistanceManhattanToTile(), or work with squared distances.
Image
Kogut
Tycoon
Tycoon
Posts: 2493
Joined: 26 Aug 2009 06:33
Location: Poland

Re: square root

Post by Kogut »

When I get money (distanse * sth_depending_on_cargo_and_time_of_travel ), distance is manhattan distance or "normal" distance?
Correct me If I am wrong - PM me if my English is bad
AIAI - AI for OpenTTD
User avatar
Zutty
Director
Director
Posts: 565
Joined: 22 Jan 2008 16:33

Re: square root

Post 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.
Last edited by Zutty on 26 Aug 2009 10:35, edited 1 time in total.
PathZilla - A networking AI - Now with tram support.
User avatar
Zutty
Director
Director
Posts: 565
Joined: 22 Jan 2008 16:33

Re: square root

Post 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.
PathZilla - A networking AI - Now with tram support.
Post Reply

Return to “OpenTTD AIs and Game Scripts”

Who is online

Users browsing this forum: No registered users and 1 guest