Skip to content

Instantly share code, notes, and snippets.

Created October 13, 2017 05:11
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Approximate magnitude of 2d and 3d vectors

Vec3 Magnitude

These C# implementations of approximate magnitude with no square roots are actually slower than calling a native implementation in Unity, but if this were implemented intelligently in C there's a good chance they would be faster. In any case, they're here because it was a pain to get the magic numbers.

Accurate to within 4.5%.

public static float MagnitudeFast (this Vector2 self)
    float dx = Mathf.Abs (self.x);
    float dy = Mathf.Abs (self.y);
    float max = Mathf.Max (dx, dy);
    float min = Mathf.Min (dx, dy);
    const float alpha = 0.96043387010f;
    const float beta = 0.39782473476f;
    return alpha * max + beta * min;

public static float MagnitudeFast (this Vector3 self)
    float min = Mathf.Abs (self.x);
    float med = Mathf.Abs (self.y);
    float max = Mathf.Abs (self.z);

    if (min > max)
        float t = max;
        max = min;
        min = t;
    if (min > med)
        float t = min;
        min = med;
        med = t;
    if (med > max)
        float t = med;
        med = max;
        max = t;

    const float alpha = 0.29870618761437979596f;
    const float beta  = 0.38928148272372526647f;
    const float gamma = 0.93980863517232523127f;
    return alpha * min + beta * med + gamma * max;
Copy link

Flawless. Thank you.

Copy link

Glad you found it useful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment