Category Archives: Mathematics

DISTANCE OF point to rectangle (without case logic)

A great solution by MultiRRomero:

function distance(Rectange r, Point p) {
  dx = max(r.x_min-p.x, 0, p.x-r.x_max);
  dy = max(r.y_min-p.y, 0, p.y-r.y_max);

  return sqrt(dx*dx + dy*dy);
}

References:

Modulo of a negative number

-b mod N = b(N-1) mod N

or:

int modulo(int x, int N){
    return (x % N + N) % N;
}

Another more standard implementation:

unsigned int modulo(int a, int m) {
    if (a % m < 0) {
        return (unsigned int ) a % m + m;
    } else {
        return (unsigned int) a % m;
    }
}

You can implement the modulo with bitwise operations for much better performance.

For powers of two this can be easily calculated as:

n % 2^i = n & (2^i - 1)

Common incorrect implementation:

(b) mod k = k (b mod k).

References:

Floating-point tolerance tests

Absolute tolerance:

  • Not good for big numbers
abs(x–y) <= tol1

Relative tolerance:

  • Not good for small numbers
abs(x–y) <= tol2 * max(abs(x), abs(y))

Combined tolerance test:

(abs(x-y) <= tol1) ||
  (abs(x-y) <= tol2 * max(abs(x), abs(y))

equal to:

abs(x-y) <= tol1 * Max(1.0f, tol2/tol1 * max(abs(x), abs(y))

which for tol1=tol2 becomes:

abs(x-y) <= tol1 * Max(1.0f, abs(x), abs(y))

 

References:

  • Real time collision detection, Christer Ericson

 

Mathematics in web pages

Online editors:

Fonts:

APIs:

Documentation:

Summary:

Examples:

Practice: