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

Improve Vec3.normalize() #1

Open
eikel opened this issue Oct 15, 2013 · 1 comment
Open

Improve Vec3.normalize() #1

eikel opened this issue Oct 15, 2013 · 1 comment

Comments

@eikel
Copy link
Member

eikel commented Oct 15, 2013

Initially reported by @ClaudiusJ as #645:

inline vec3_t& normalize() {
    const value_t ls = lengthSquared();
    if(ls==0) {
        std::cerr<<"Cannot normalize a vector with zero length."<<std::endl;
        return *this;
    }else if( std::abs(ls-static_cast<value_t>(1.0)) <= epsilon ){
        return *this;
    }else{
        const value_t l = 1/std::sqrt(ls);
        vec[0] *= l;
        vec[1] *= l;
        vec[2] *= l;
        return *this;
    }
}
  • Calculate sqrt only when necessary.
  • Don't normalize a vector that is almost 1 (due to floating point errors). Dividing those numbers won't result in a vector that has exactly a length of 1.0 anyway. The question is: what is a good choice for epsilon? It should be chosen in a way, that a normalized vector is not touched when normalized again.
@eikel
Copy link
Member Author

eikel commented Jun 15, 2016

I would replace comparison by zero to an inequality. Instead of zero, the epsilon value could be used. Furthermore, remove the error message.

inline vec3_t& normalize() {
    const value_t ls = lengthSquared();
    if (ls > 0) {
        const value_t l = 1 / std::sqrt(ls);
        vec[0] *= l;
        vec[1] *= l;
        vec[2] *= l;
    }
    return *this;
}

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

No branches or pull requests

1 participant