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.
Initially reported by @ClaudiusJ as #645: