MCPcopy Create free account
hub / github.com/OpenTTD/OpenTTD / DivideApprox

Function DivideApprox

src/core/math_func.cpp:22–34  ·  view source on GitHub ↗

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

Source from the content-addressed store, hash-verified

20 * @return a/b or (a/b)+1.
21 */
22int DivideApprox(int a, int b)
23{
24 int random_like = ((a + b) * (a - b)) % b;
25
26 int remainder = a % b;
27
28 int ret = a / b;
29 if (abs(random_like) < abs(remainder)) {
30 ret += ((a < 0) ^ (b < 0)) ? -1 : 1;
31 }
32
33 return ret;
34}
35
36/**
37 * Compute the integer square root.

Callers 3

EstimateDestinationsMethod · 0.85
BuildCargoListMethod · 0.85
math_func.cppFile · 0.85

Calls 1

absFunction · 0.85

Tested by

no test coverage detected