Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

I have made function in Matlab, that shale calculate the rotation matrix for fi degrees around unit vector k.

function R = rot(k,fi)
    rad = fi*(pi/180);

    % This is just to make it easyer to read!
    x = k(1);
    y = k(2);
    z = k(3);

    % Create a 3x3 zero matrix
    R = zeros(3,3);
    % We use the formual for rotationg matrix about a unit vector k

    R(1,1) = cos(rad)+x^2*(1-cos(rad));
    R(1,2) = x*y*(1-cos(rad))-z*sin(rad);
    R(1,3) = x*z*(1-cos(rad))+y*sin(rad);

    R(2,1) = y*x*(1-cos(rad))+z*sin(rad);
    R(2,2) = cos(rad)+y^2*(1-cos(rad));
    R(2,3) = y*z*(1-cos(rad))-x*sin(rad);

    R(3,1) = z*x*(1-cos(rad))-y*sin(rad);
    R(3,2) = z*y*(1-cos(rad))+x*sin(rad);
    R(3,3) = cos(rad)+z^2*(1-cos(rad));

But it don't seem to work, i have a test rules

rot(k,0) == I
rot(k,fi) == rot(k,fi+360)
rot(-k,fi) == transpose(rot(k,fi))
rot(k,f1)*rot(k,f2) == rot(k,f1+f2)
rot(k,fi)*k == k

My function is always successfull on rule nr 1, 3 and sometime on 2. What am i doing wrong here? is my function not correct?

share|improve this question
How different are the results? Is it a case of rounding error? Also, $k$ must be a unit vector. –  Daryl Oct 24 '12 at 21:13
If it's the test rot(k,fi) == rot(k,fi+360) that's failing, this is caused almost certainly by rounding errors -- you're only using the second argument as an argument for the sine and cosine, which should be invariant. One would expect rounding errors, though -- are these comparisons exact? If so, I'd be surprised if the test didn't fail. –  joriki Oct 24 '12 at 21:24
The diffrence are small! example sometime are 0 compared with a -0 –  DoomStone Oct 24 '12 at 22:17
add comment

1 Answer

You are using equality checks on floating point values.

I suggest you do not check for equality but see whether the absolute difference is less than epsilon.

share|improve this answer
add comment

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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