mirror of https://github.com/OpenTTD/OpenTTD
(svn r25347) -Add: function for deterministic approximate division
parent
db671ffb86
commit
dfad8317aa
|
@ -47,6 +47,27 @@ int GreatestCommonDivisor(int a, int b)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deterministic approximate division.
|
||||||
|
* Cancels out division errors stemming from the integer nature of the division over multiple runs.
|
||||||
|
* @param a Dividend.
|
||||||
|
* @param b Divisor.
|
||||||
|
* @return a/b or (a/b)+1.
|
||||||
|
*/
|
||||||
|
int DivideApprox(int a, int b)
|
||||||
|
{
|
||||||
|
int random_like = ((a + b) * (a - b)) % b;
|
||||||
|
|
||||||
|
int remainder = a % b;
|
||||||
|
|
||||||
|
int ret = a / b;
|
||||||
|
if (abs(random_like) < abs(remainder)) {
|
||||||
|
ret += ((a < 0) ^ (b < 0)) ? -1 : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Compute the integer square root.
|
* Compute the integer square root.
|
||||||
* @param num Radicand.
|
* @param num Radicand.
|
||||||
|
|
|
@ -317,6 +317,7 @@ static inline uint ToPercent16(uint i)
|
||||||
|
|
||||||
int LeastCommonMultiple(int a, int b);
|
int LeastCommonMultiple(int a, int b);
|
||||||
int GreatestCommonDivisor(int a, int b);
|
int GreatestCommonDivisor(int a, int b);
|
||||||
|
int DivideApprox(int a, int b);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Computes ceil(a / b) for non-negative a and b.
|
* Computes ceil(a / b) for non-negative a and b.
|
||||||
|
|
Loading…
Reference in New Issue