# Vector normalization issues

Hi,

I am having problems simply normalizing a vector. Here is the code :

``````
int diffX, diffY;

diffX = 300;
diffY = 300;

ofVec2f dirVec = (diffX, diffY);
dirVec.normalize();

cout << "dirVec x and y : " << dirVec.x << " " << dirVec.y << "\n";

``````

I would expect dirVec to be equal to (root(2), root(2)).

What did I do wrong ?

Bonus question : does the normalize() function cost much ? (ie, does it use the very costly square root calculation, or something faster ?)

you can’t set a vector like this:

ofVec2f dirVec = (diffX, diffY);

you can do either this:

ofVec2f dirVec(diffX, diffY);

or this:

ofVec2f dirVec; dirVec.set(diffX, diffY);

doing it they way you are doing it only sets “x”, which leads to a normalized vector of (1,0).

hope that helps!
zach

ps: about how expensive it is, you can see the code in ofVec2.h, it is using a sqrt:

inline ofVec2f& ofVec2f::normalize() {
float length = (float)sqrt(x*x + y*y);
if( length > 0 ) {
x /= length;
y /= length;
}
return *this;
}

hallelujah thanks