Skip to content

Instantly share code, notes, and snippets.

@karlgluck
Created October 13, 2017 05:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save karlgluck/785bc181c4b000575f34ce2187c13af0 to your computer and use it in GitHub Desktop.
Save karlgluck/785bc181c4b000575f34ce2187c13af0 to your computer and use it in GitHub Desktop.
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;
    }
@A-Conspiracy-Theory
Copy link

Flawless. Thank you.

@karlgluck
Copy link
Author

Glad you found it useful!

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