Skip to content

Improve Vec3.normalize() #1

Description

@eikel

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions