Skip to content

Instantly share code, notes, and snippets.

@vyo
Forked from karlgluck/VectorMagnitude.md
Created January 26, 2018 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vyo/6a24d0284b579ef426354ee73e1cfbcb to your computer and use it in GitHub Desktop.
Save vyo/6a24d0284b579ef426354ee73e1cfbcb 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;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment