3
\$\begingroup\$

When I normalize vectors I receive very strange results. The lengths of the normalized vectors range from 1.0 to almost 1.5. The functions are all written by me, but I just can't find a mistake in my algorithm. When I normalize I just divide all components of the vector by the vector's length.

public double length(){
    return Math.sqrt(x*x + y*y);
}

public void normalize(){
    if(length() > 0){
        x /= length();
        y /= length();
    }
}

Is this supposed to happen? I mean I can see the length ranging from 0.9 to 1.1 at worst, but this is just overwhelming.

Cheers

\$\endgroup\$
1
  • \$\begingroup\$ For your vector functions, how are they any different from other math functions? If it truly is a function, make it, like all the functions in the Math class, static. Maybe you need to put this into StaticVectorFunctions? \$\endgroup\$ – Thufir Dec 27 '13 at 11:15
9
\$\begingroup\$

The third call to length() in your function uses the updated x value. You really don't want that.

Calculate the length once, then divide x and y.

double len = length();
if (len > 0) {
  x /= len;
  y /= len;
}
\$\endgroup\$
1
  • \$\begingroup\$ Yeah, I realized that almost immediately after posting. But still thanks for taking the time to answer. It might be helpful to others stuck in the same tricky problem. \$\endgroup\$ – Kipras Oct 19 '13 at 19:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.