# Interpolating continous rotation

I need some help with animating a rotating object.

I am attempting to rotate the object with the help of a generated rotation matrix. I insert a keyframe for for every 5 frames with quaternion coordinates.

Here is some example code:

import bpy
from mathutils import Vector, Matrix

f = lambda angl: Matrix(((cos(angl), -sin(angl), 0, 0),
(sin(angl), cos(angl), 0, 0),
(0, 0, 1, 0),
(0, 0, 0, 1)))

obj = bpy.data.objects['Cube']

obj.animation_data_clear()

obj.rotation_mode = 'QUATERNION'

frame_start = bpy.context.scene.frame_start
frame_end = bpy.context.scene.frame_end
step = 5

for i in range(frame_start, frame_end, step):
loc, rot, sca = obj.matrix_world.decompose()
mloc = Matrix.Translation(loc)
mrot = rot.to_matrix().to_4x4()
msca = Matrix.Scale(sca, 4, (1, 0, 0)) * Matrix.Scale(sca, 4,     (0,1,0)) * Matrix.Scale(sca, 4, (0,0,1))

Rm = f(pi/frame_end*8*i)
obj.matrix_world = mloc * Rm * msca
obj.keyframe_insert(data_path='rotation_quaternion', frame=i)


The mathematical model works just fine. The cube is rotated around the z axis like it should.

My problem arises when blender transforms the rotation matrix in obj.matrix_world to quaternion coordinates. The resulting curve becomes: The cube in this case rotates one turn. Then blenders interpolation causes the cube to quickly spin back 360 degrees before countinuing its rotation. The problem may be tied with how I insert the keyframes with quaternions.

I would like the rotation to appear continous without this back-spin. There are modifiers that can take a rotation and repeat it, but that wont work for me since i want to visualize a mathematical model.

So my question is if anyone has any idea on how to mend this.

Thanks.