# How to randomly draw Quaternions within a specific range of Euler angles for rotation?

I am pretty new to Quaternions so please bear with me. I want to draw random Quaternion samples so that their Euler angle equivalent would range within [-30, +30] degrees on each axis. Currently, I know how to sample Quaternions from the full range ([-180, +180]) using the code below but I don't know how to modify the code so that I can get samples within the range [-30, +30]. Can anyone help me with that?

I'm not sure if this is helpful to answer this question but here's a piece of information: I eventually want to convert the sampled Quaternion to Euler angles an apply the Euler rotation in some 3D shapes. The order of rotation in the software I'm using to do this is XYZ meaning that it first rotates the 3D shape along the X axis, then Y axis and then Z axis.

import numpy as np
def sample_Quaternion():
r = np.random.uniform(0, 1 - 0.001, 3)
while np.linalg.norm(r) > 1:
r = np.random.uniform(0, 1 - 0.001, 3) # Just to keep the L2 norm within [0, 1.0)
w = [np.sqrt(1 - (r[0]*r[0] + r[1]*r[1] + r[2]*r[2]))]
r = np.concatenate(r, w) # the output of this would represent (x, y, z, w)
return r

• "I eventually want to convert the sampled Quaternion to Euler angles an apply the Euler rotation in some 3D shapes." Please stop wanting to do that. Euler angles are bad, and you've taken a big step by moving away from them. Keep your orientations as quaternions; don't convert to/from Euler angles. Oct 28 '18 at 1:48
• @NicolBolas I really want to avoid using Euler angles but unfortunately I have to use Euler angles for a part of my current project. Could you also take a look at my new, relevant question here and see if you can provide an answer for this one?
– Amir
Oct 28 '18 at 16:57
• @Amir Why do not you just use matrices to rotate? Nov 2 '18 at 2:51

The simplest way to do this would be to generate the Euler angles randomly, then use them to create the quaternion. Most existing quaternion implementations in game engines and 3D math libraries will have a FromEuler ( Vector3 ) function.