Explain quaternion slerp for rotation interpolation. Why use quaternions instead of Euler angles to avoid gimbal lock? Write the spherical linear interpolation formula.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
where θ is the angle between the two quaternions, calculated from their dot product.
Now I'll implement this with working code examples:
python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
class Quaternion:
def __init__(self, w, x, y, z):
"""Initialize quaternion q = w + xi + yj + zk"""
self.w = w
self.x = x
self.y = y
self.z = z
def normalize(self):
"""Normalize to unit quaternion"""
magnitude
I need to complete the normalize method and continue with the rest of the implementation. The magnitude calculation divides each component by the norm to ensure the quaternion has unit length. Then I'll add helper methods for dot products and arithmetic operations, followed by the core slerp function that performs the spherical interpolation using the angle between quaternions.
The slerp implementation normalizes both input quaternions, computes their dot product to determine the shortest rotation path, clamps the result to handle numerical precision, calculates the angle between them using inverse cosine, and then applies the interpolation formula using sine of the angle to smoothly blend between the two rotations. .5)
code
w = cr * cp * cy + sr * sp * sy
x = sr * cp * cy - cr * sp * sy
y = cr * sp * cy + sr * cp * sy
z = cr * cp * sy - sr * sp * cy
return Quaternion(w, x, y, z)
Now I'll demonstrate how quaternion slerp compares to euler angle interpolation. Starting with two quaternions—one at identity and another representing a rotation of π/4 around roll, π/6 around pitch, and π/3 around yaw—I can interpolate between them at different time steps and convert back to euler angles to see the smooth rotation progression.
For the gimbal lock problem, I'm setting up euler angles where the pitch approaches 90 degrees. Linear interpolation between [0, 0, 0] and [0, π/2, 0] will reveal how euler angles break down near this singularity, whereas quaternions handle it gracefully. print("\nObservation: Quaternion slerp maintains smooth rotation without singularities!")
I'm computing the angular velocity differences between consecutive interpolated quaternions to show how Slerp maintains constant angular velocity while linear interpolation produces uneven rotational speeds.
print("=" * 60)
print("KEY ADVANTAGES OF QUATERNIONS OVER EULER ANGLES:")
print("=" * 60)
Quaternions eliminate gimbal lock by existing in 4D space without singular points, enable smooth constant-velocity interpolation through Slerp, provide continuous rotation representation without undefined configurations, compute faster than matrices, and compose rotations simply through multiplication.
Gimbal lock occurs with Euler angles because at pitch = ±90°, the rotation axes become coplanar, collapsing three degrees of freedom into two and preventing smooth interpolation through that singularity.
The Slerp formula maintains constant angular velocity during interpolation:
To apply it, I compute the dot product between quaternions, negate q₂ if the dot product is negative to take the shorter path, calculate the angle θ = arccos(dot_product), then apply the formula or fall back to linear interpolation when θ is near zero, finally normalizing the result.
The slerp formula itself is: slerp(q₁, q₂, t) = (sin((1-t)θ) / sin(θ)) * q₁ + (sin(tθ) / sin(θ)) * q₂. I can implement this directly or use a library function, and I should include code examples showing both the mathematical approach and practical usage patterns.
What happens:
Euler angles represent rotations as three successive rotations (pitch, roll, yaw). When pitch = ±90°, the first and third rotation axes become aligned—losing one degree of freedom.
python
# Gimbal Lock Visualization
import numpy as np
# At pitch = 90°, roll and yaw affect the SAME axis
roll = 45° # Rotate around X
pitch = 90° # Rotate around Y (but X-axis rotates too!)
yaw = 30° # Rotate around Z - BUT Z IS NOW ALIGNED WITH X!
# Problem: Can't distinguish between roll and yaw applications
# Result: Smooth interpolation breaks down
Why Quaternions Avoid Gimbal Lock
Aspect
Euler Angles
Quaternions
Space
3D (has singularities)
4D hypersphere (no singularities)
Gimbal Lock
✗ Occurs at ±90° pitch
✓ Never occurs
Representation
3 sequential rotations
Single rotation around arbitrary axis
Interpolation
Jerky near singularities
Smooth, constant angular velocity
The Slerp Formula
Spherical Linear Interpolation:
Slerp(q1,q2
Where:
θ = arccos(q₁ · q₂) — angle between quaternions
t ∈ [0,1] — interpolation parameter
q₁, q₂ — unit quaternions
Complete Implementation
python
import numpy as np
class Quaternion:
def __init__(self, w, x, y, z):
"""Quaternion q = w + xi + yj + zk"""
self.w, self.x, self.y, self.z = w, x, y, z
def normalize(self):
"""Normalize to unit quaternion"""
mag = np.sqrt(self.w**2 + self.x**2 + self.y**2 + self.z**2)
return Quaternion(self.w/mag, self.x/mag, self.y/mag, self.z/mag)
def dot(self, other):
"""Dot product"""
return self.w*other.w + self.x*other.x + self.y*other.y + self.z*other.z
def __add__(self, other):
return Quaternion(self.w+other.w, self.x+other.x,
self.y+other.y, self.z+other.z)
def __mul__(self, scalar):
return Quaternion(self.w*scalar, self.x*scalar,
self.y*scalar, self.z*scalar)
def slerp(q1, q2, t):
"""
Spherical Linear Interpolation
Args:
q1, q2: Start and end quaternions
t: Interpolation parameter [0, 1]
Returns:
Interpolated quaternion
"""
# Normalize inputs
q1 = q1.normalize()
q2 = q2.normalize()
# Compute dot product
dot_product = q1.dot(q2)
# If dot < 0, negate q2 to take shorter path on 4D sphere
if dot_product < 0.0:
q2 = q2 * -1
dot_product = -dot_product
# Clamp to [-1, 1] to avoid acos issues
dot_product = np.clip(dot_product, -1.0, 1.0)
# Compute angle
theta = np.arccos(dot_product)
sin_theta = np.sin(theta)
# Handle nearly-parallel quaternions (use linear interpolation)
if sin_theta < 0.001:
result = q1 * (1 - t) + q2 * t
else:
# Slerp formula
w1 = np.sin((1 - t) * theta) / sin_theta
w2 = np.sin(t * theta) / sin_theta
result = q1 * w1 + q2 * w2
return result.normalize()
def euler_to_quaternion(roll, pitch, yaw):
"""Convert Euler angles (radians) to quaternion"""
cy, sy = np.cos(yaw/2), np.sin(yaw/2)
cp, sp = np.cos(pitch/2), np.sin(pitch/2)
cr, sr = np.cos(roll/2), np.sin(roll/2)
w = cr * cp * cy + sr * sp * sy
x = sr * cp * cy - cr * sp * sy
y = cr * sp * cy + sr * cp * sy
z = cr * cp * sy - sr * sp * cy
return Quaternion(w, x, y, z)
def quaternion_to_euler(q):
"""Convert quaternion to Euler angles (radians)"""
# Roll
sinr = 2 * (q.w * q.x + q.y * q.z)
cosr = 1 - 2 * (q.x**2 + q.y**2)
roll = np.arctan2(sinr, cosr)
# Pitch
sinp = 2 * (q.w * q.y - q.z * q.x)
pitch = np.arcsin(np.clip(sinp, -1, 1))
# Yaw
siny = 2 * (q.w * q.z + q.x * q.y)
cosy = 1 - 2 * (q.y**2 + q.z**2)
yaw = np.arctan2(siny, cosy)
return roll, pitch, yaw
Demonstration: Gimbal Lock vs Slerp
python
print("=" * 70)
print("GIMBAL LOCK PROBLEM")
print("=" * 70)
# Euler angle interpolation approaching gimbal lock (pitch → 90°)
print("\n1. LINEAR EULER ANGLE INTERPOLATION (PROBLEMATIC)")
print("-" * 70)
euler_start = np.array([0, 0, 0])
euler_end = np.array([0, np.pi/2, 0]) # pitch = 90° (gimbal lock!)
for t in [0, 0.25, 0.5, 0.75, 1.0]:
euler = euler_start * (1-t) + euler_end * t
print(f"t={t:.2f}: roll={np.degrees(euler[0]):6.1f}°, "
f"pitch={np.degrees(euler[1]):6.1f}°, yaw={np.degrees(euler[2]):6.1f}°")
print("\n❌ PROBLEM: Roll and yaw become identical near pitch=90°!")
print(" Motion becomes jerky and unpredictable")
# Quaternion interpolation of same rotation
print("\n\n2. QUATERNION SLERP INTERPOLATION (SMOOTH)")
print("-" * 70)
q_start = euler_to_quaternion(0, 0, 0)
q_end = euler_to_quaternion(0, np.pi/2, 0)
for t in [0, 0.25, 0.5, 0.75, 1.0]:
q = slerp(q_start, q_end, t)
roll, pitch, yaw = quaternion_to_euler(q)
print(f"t={t:.2f}: roll={np.degrees(roll):6.1f}°, "
f"pitch={np.degrees(pitch):6.1f}°, yaw={np.degrees(yaw):6.1f}°")
print("\n✓ SUCCESS: Smooth interpolation through gimbal lock region!")
print("\n" + "=" * 70)
print("ANGULAR VELOCITY COMPARISON")
print("=" * 70)
# Generate full interpolation paths
t_values = np.linspace(0, 1, 50)
# Linear Euler (problematic)
euler_path = np.array([euler_start * (1-t) + euler_end * t for t in t_values])
# Slerp (smooth)
slerp_path = np.array([slerp(q_start, q_end, t) for t in t_values])
# Compute angular velocities
def quat_to_array(q):
return np.array([q.w, q.x, q.y, q.z])
slerp_angles = []
for i in range(1, len(slerp_path)):
dot = np.sum(quat_to_array(slerp_path[i]) * quat_to_array(slerp_path[i-1]))
angle = 2 * np.arccos(np.clip(abs(dot), 0, 1))
slerp_angles.append(np.degrees(angle))
print(f"\nSlerp angular change per step:")
print(f" Min: {min(slerp_angles):.2f}°")
print(f" Max: {max(slerp_angles):.2f}°")
print(f" Mean: {np.mean(slerp_angles):.2f}°")
print(f" StdDev: {np.std(slerp_angles):.4f}°")
print(f"\n→ SLERP maintains nearly CONSTANT angular velocity!")