Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vector3::normalize() returns wrong result #533

Open
paexter opened this issue Aug 19, 2021 · 2 comments
Open

Vector3::normalize() returns wrong result #533

paexter opened this issue Aug 19, 2021 · 2 comments
Milestone

Comments

@paexter
Copy link

paexter commented Aug 19, 2021

Normalizing a vector vec with a very large component does not not lead to the expected result.

vec: Vector(0, 0, 3.40282e+38)
vec.length(): inf
vec.lengthInverted(): 0
vec.normalized(): Vector(0, 0, 0)

The expected result is vec.normalized(): Vector(0, 0, 1)

@pezcode
Copy link
Contributor

pezcode commented Aug 19, 2021

You can probably mitigate the intermediate length overflow by using something like (vec/Math::abs(vec).max()).normalized()

@mosra mosra added this to the 2021.0a milestone Sep 12, 2021
@mosra
Copy link
Owner

mosra commented Sep 12, 2021

(Sorry for the extremely late reply, only now going through the notification pile.)

Ah well, numerical issues. There's a tradeoff between doing the simplest possible thing (and being fast), or being immune to every possible corner case and ending up with a similar monstrosity as std::lerp(). I'd need to do some research, do you know about any "usual" way how this is being done robustly? I looked at Eigen's normalized() and it suffers from the same problem:

  RealScalar z = n.squaredNorm();
  // NOTE: after extensive benchmarking, this conditional does not impact performance, at least on recent x86 CPU
  if(z>RealScalar(0))
    return n / numext::sqrt(z);
  else
    return n;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Development

No branches or pull requests

3 participants