3 ms·
Yes. //---------------------------------------------- void MVec3::normalize() { // calculate length. float len = sqrtf( x*x + y*y + z*z );
by palish 15y ago
Yes.
//----------------------------------------------
void
MVec3::normalize()
{
// calculate length.
float len = sqrtf( x*x + y*y + z*z );
// verify length is not zero.
assert( len != 0.0f );
if ( len == 0.0f )
len = 1.0f;
// divide by length.
len = (1.0f / len);
x *= len;
y *= len;
z *= len;
}
- pama 15y agoThanks. However, normalization is a rather simple case and the solution you propose works as expected. I posit that most code performing floating point division doesn't check all corner cases correctly; those that do are codes written by people who worry about NaN and the correct type of Inf.
- Someone 15y agoJust curious (and only marginally, if at all, on topic): - Why is that assert there? - Why aren't that "len = (1.0f / len)" and the "= len" statements in an else clause? (are there CPUs where always doing the division and those 3 multiplications is faster? Will compilers optimize that, anyways? Are there IEEE subtleties that make x= 1.0f not a no-op?) - Wouldn't it, on some platforms, be better to use double for intermediate results?
- barrettcolin 15y agoI've had fairly heated arguments about this in the past and I'm curious to know if anyone else holds the same opinion: I contend that a normalize function is a really bad place to put an assert. Chances are the normalize will be called frequently and the assert check, in debug mode, will have an impact on performance (this goes for assert checks inside other frequently called functions too). The cumulative effect is a debug build that becomes unusably slow relative to the optimized build without the asserts, which rather defeats the purpose of having it in the first place: if you can't use it to find problems, then what's the point? (I'm remembering this being the case more often than not when working on games for the Xbox 360 or PS3).
- palish 15y agoI've been bitten by not having asserts (and, conversely, saved by having them) that I don't hold to the philosophy of "don't use asserts out of performance considerations". assert( len != 0.0f ); If that alone is enough to slow down your program by any significant margin, then you're doing something wrong. That said, I've experienced your standpoint --- A debug mode which was unusably slow. However, that results from programmers who rely too much on the optimizer. STL, for example, can perform very slowly in debug mode in certain circumstances.
- barrettcolin 15y agoIt was recollection on my part; not backed by empirical evidence. For this exact case, though: wouldn't you better handle this with floating point exceptions?