HomeProjects

Faster trig functions

Up to 30% faster trig in the powertrain math library, by using approximations that fit the input domain.

General Motors · embedded C, math libraries

While on the Infrastructure Software team, where I owned the memory manager and bootloader, I briefly took over the powertrain math libraries to cover a staffing gap. An internal customer raised concerns about the performance of the trig functions, so I profiled the existing library and looked at alternatives. As it happened, I was also writing a physics engine for an iPhone project at the time that leaned on the same functions.

The pattern I found is that many math libraries get their speed by approximating a function over a narrow input domain. If the domain satisfies the requirements, the faster function is a legitimate substitute. I was able to replace most of the trig functions this way, for speed improvements of up to 30%.

Example: arctan

I can't share the production code, but a good candidate for arctan came from an IEEE Signal Processing Magazine article on efficient approximations. For |x| ≤ 1:

arctan(x) ≈ x·π/4 + 0.273·x·(1 − |x|)

This small program writes the approximation and the library function out side by side so they can be compared:

#include <math.h>
#include <stdio.h>

static const float PI = 3.141592654f;

/* Valid for -1 <= x <= 1. */
static float arctan_approx(float x)
{
    return x * PI / 4.0f + 0.273f * x * (1.0f - fabsf(x));
}

int main(void)
{
    FILE *fp = fopen("arctan.csv", "w");
    float x;

    if (fp == NULL) {
        return 1;
    }
    for (x = -1.0f; x <= 1.0f; x += 0.01f) {
        fprintf(fp, "%f,%f,%f\n", x, arctan_approx(x), atanf(x));
    }
    fclose(fp);
    return 0;
}
Spreadsheet comparing the arctan approximation with the library function across the domain, with a plot of both
Approximation versus the library function. The fit is only good inside the intended domain, which is the point.

There is a little more in the GitHub repo.