0
# Basic Operations
1
2
Fundamental quaternion operations including arithmetic, comparison, normalization, type conversion, and component access.
3
4
## Capabilities
5
6
### Arithmetic Operations
7
8
Standard mathematical operations with proper quaternion algebra.
9
10
```python { .api }
11
def __add__(self, other):
12
"""
13
Add two quaternions element-wise.
14
15
Parameters:
16
other: Quaternion or scalar
17
18
Returns:
19
Quaternion: Sum of quaternions
20
"""
21
22
def __sub__(self, other):
23
"""
24
Subtract quaternions element-wise.
25
26
Parameters:
27
other: Quaternion or scalar
28
29
Returns:
30
Quaternion: Difference of quaternions
31
"""
32
33
def __mul__(self, other):
34
"""
35
Multiply quaternions using quaternion product (non-commutative).
36
37
Parameters:
38
other: Quaternion or scalar
39
40
Returns:
41
Quaternion: Product of quaternions
42
"""
43
44
def __div__(self, other):
45
"""
46
Divide quaternions by multiplying with inverse.
47
48
Parameters:
49
other: Quaternion or scalar (non-zero)
50
51
Returns:
52
Quaternion: Quotient of quaternions
53
54
Raises:
55
ZeroDivisionError: If divisor is zero quaternion
56
"""
57
58
def __pow__(self, exponent):
59
"""
60
Raise quaternion to a power using polar decomposition.
61
62
Parameters:
63
exponent: float, real-valued exponent
64
65
Returns:
66
Quaternion: Quaternion raised to the power
67
"""
68
```
69
70
**Usage Examples:**
71
72
```python
73
from pyquaternion import Quaternion
74
75
q1 = Quaternion(1, 0, 0, 0)
76
q2 = Quaternion(0, 1, 0, 0)
77
78
# Basic arithmetic
79
sum_q = q1 + q2 # Element-wise addition
80
diff_q = q1 - q2 # Element-wise subtraction
81
product_q = q1 * q2 # Quaternion multiplication (non-commutative)
82
quotient_q = q1 / q2 # Division via inverse
83
power_q = q1 ** 2 # Exponentiation
84
85
# Scalar operations
86
scaled_q = q1 * 2.0 # Scalar multiplication
87
divided_q = q1 / 2.0 # Scalar division
88
```
89
90
### In-place Operations
91
92
Modify quaternions in-place for efficient computation.
93
94
```python { .api }
95
def __iadd__(self, other):
96
"""In-place addition."""
97
98
def __isub__(self, other):
99
"""In-place subtraction."""
100
101
def __imul__(self, other):
102
"""In-place multiplication."""
103
104
def __idiv__(self, other):
105
"""In-place division."""
106
107
def __ipow__(self, other):
108
"""In-place exponentiation."""
109
```
110
111
### Unary Operations
112
113
```python { .api }
114
def __neg__(self):
115
"""
116
Negate all quaternion components.
117
118
Returns:
119
Quaternion: Negated quaternion (-w, -x, -y, -z)
120
"""
121
122
def __abs__(self):
123
"""
124
Get the norm (magnitude) of the quaternion.
125
126
Returns:
127
float: L2 norm of quaternion 4-vector
128
"""
129
```
130
131
### Matrix Operations
132
133
Support for matrix multiplication operator (@).
134
135
```python { .api }
136
def __matmul__(self, other):
137
"""
138
Matrix multiplication (@ operator) - computes dot product of quaternion arrays.
139
140
Parameters:
141
other: Quaternion
142
143
Returns:
144
float: Dot product of quaternion 4-vectors
145
"""
146
```
147
148
### Comparison Operations
149
150
```python { .api }
151
def __eq__(self, other):
152
"""
153
Test equality with tolerance.
154
155
Uses numpy.allclose with rtol=1e-13, atol=1e-14
156
157
Parameters:
158
other: Quaternion or convertible type
159
160
Returns:
161
bool: True if quaternions are equal within tolerance
162
"""
163
164
def __hash__(self):
165
"""
166
Hash support for use in sets and dictionaries.
167
168
Returns:
169
int: Hash of quaternion tuple
170
"""
171
```
172
173
### Utility Methods
174
175
Static methods for angle conversion and quaternion validation.
176
177
```python { .api }
178
@staticmethod
179
def to_degrees(angle_rad):
180
"""
181
Convert radians to degrees.
182
183
Parameters:
184
angle_rad: float, angle in radians
185
186
Returns:
187
float: Angle in degrees
188
"""
189
190
@staticmethod
191
def to_radians(angle_deg):
192
"""
193
Convert degrees to radians.
194
195
Parameters:
196
angle_deg: float, angle in degrees
197
198
Returns:
199
float: Angle in radians
200
"""
201
202
def is_unit(self, tolerance=1e-14):
203
"""
204
Check if quaternion is a unit quaternion (within tolerance).
205
206
Parameters:
207
tolerance: float, tolerance for unit length check
208
209
Returns:
210
bool: True if |norm - 1| < tolerance
211
"""
212
```
213
214
**Usage Examples:**
215
216
```python
217
from pyquaternion import Quaternion
218
import math
219
220
# Angle conversion
221
degrees = Quaternion.to_degrees(math.pi) # 180.0
222
radians = Quaternion.to_radians(90) # 1.5707963267948966
223
224
# Unit quaternion check
225
q = Quaternion(axis=[0, 1, 0], degrees=90)
226
print(q.is_unit()) # True
227
228
q_scaled = q * 2.0
229
print(q_scaled.is_unit()) # False
230
```
231
232
### Core Properties
233
234
Essential quaternion properties for mathematical operations.
235
236
```python { .api }
237
@property
238
def conjugate(self):
239
"""
240
Quaternion conjugate (vector part negated).
241
242
For unit quaternions, this equals the inverse.
243
244
Returns:
245
Quaternion: New quaternion with negated vector part (w, -x, -y, -z)
246
"""
247
248
@property
249
def inverse(self):
250
"""
251
Quaternion inverse for non-zero quaternions.
252
253
For unit quaternions, this is the inverse rotation.
254
255
Returns:
256
Quaternion: Multiplicative inverse
257
258
Raises:
259
ZeroDivisionError: If quaternion is zero (0, 0, 0, 0)
260
"""
261
262
@property
263
def norm(self):
264
"""
265
L2 norm (magnitude) of quaternion 4-vector.
266
267
Should be 1.0 for unit quaternions (versors).
268
269
Returns:
270
float: sqrt(w² + x² + y² + z²)
271
"""
272
273
@property
274
def magnitude(self):
275
"""Alias for norm."""
276
277
@property
278
def normalised(self):
279
"""
280
Get unit quaternion copy.
281
282
Returns:
283
Quaternion: New quaternion with norm = 1.0
284
"""
285
286
@property
287
def unit(self):
288
"""Alias for normalised."""
289
```
290
291
### Normalization Methods
292
293
```python { .api }
294
def is_unit(self, tolerance=1e-14):
295
"""
296
Check if quaternion is of unit length.
297
298
Parameters:
299
tolerance: Maximum deviation from unit length
300
301
Returns:
302
bool: True if |norm - 1| < tolerance
303
"""
304
305
def _normalise(self):
306
"""
307
Normalize quaternion in-place to unit length.
308
309
Modifies the quaternion object directly.
310
No effect if quaternion is zero.
311
"""
312
313
def _fast_normalise(self):
314
"""
315
Fast in-place normalization using approximation when appropriate.
316
317
Uses Padé approximation for small errors, full sqrt otherwise.
318
"""
319
```
320
321
**Usage Examples:**
322
323
```python
324
q = Quaternion(2, 0, 0, 0)
325
326
# Check and normalize
327
print(f"Is unit: {q.is_unit()}") # False
328
print(f"Norm: {q.norm}") # 2.0
329
330
# Get normalized copy
331
unit_q = q.normalised
332
print(f"Original: {q}") # (2, 0, 0, 0)
333
print(f"Normalized: {unit_q}") # (1, 0, 0, 0)
334
335
# In-place normalization
336
q._normalise()
337
print(f"After normalize: {q}") # (1, 0, 0, 0)
338
```
339
340
### Type Conversion
341
342
Convert quaternions to other Python types.
343
344
```python { .api }
345
def __int__(self):
346
"""
347
Convert to int using only the real component.
348
349
Returns:
350
int: Truncated real component
351
"""
352
353
def __float__(self):
354
"""
355
Convert to float using only the real component.
356
357
Returns:
358
float: Real component as float
359
"""
360
361
def __complex__(self):
362
"""
363
Convert to complex using real and first imaginary components.
364
365
Returns:
366
complex: complex(w, x)
367
"""
368
369
def __bool__(self):
370
"""
371
Boolean conversion - True if non-zero quaternion.
372
373
Returns:
374
bool: False only for zero quaternion (0, 0, 0, 0)
375
"""
376
```
377
378
### Component Access
379
380
Access individual quaternion components.
381
382
```python { .api }
383
@property
384
def scalar(self):
385
"""Real/scalar component (w)."""
386
387
@property
388
def vector(self):
389
"""Imaginary/vector components as numpy array [x, y, z]."""
390
391
@property
392
def real(self):
393
"""Alias for scalar."""
394
395
@property
396
def imaginary(self):
397
"""Alias for vector."""
398
399
@property
400
def w(self):
401
"""Scalar component."""
402
403
@property
404
def x(self):
405
"""First vector component."""
406
407
@property
408
def y(self):
409
"""Second vector component."""
410
411
@property
412
def z(self):
413
"""Third vector component."""
414
415
@property
416
def elements(self):
417
"""All quaternion elements as numpy array [w, x, y, z]."""
418
419
def __getitem__(self, index):
420
"""Get component by index (0=w, 1=x, 2=y, 3=z)."""
421
422
def __setitem__(self, index, value):
423
"""Set component by index (0=w, 1=x, 2=y, 3=z)."""
424
```
425
426
### String Representation
427
428
```python { .api }
429
def __str__(self):
430
"""
431
Informal string representation.
432
433
Returns:
434
str: Format like "1.000 +0.000i +0.000j +0.000k"
435
"""
436
437
def __repr__(self):
438
"""
439
Official string representation for debugging.
440
441
Returns:
442
str: Valid Python expression to recreate quaternion
443
"""
444
445
def __format__(self, formatstr):
446
"""
447
Custom formatting support.
448
449
Parameters:
450
formatstr: Format specification (follows float format rules)
451
452
Returns:
453
str: Formatted quaternion string
454
"""
455
```
456
457
### Copy Operations
458
459
```python { .api }
460
def __copy__(self):
461
"""Shallow copy support."""
462
463
def __deepcopy__(self, memo):
464
"""Deep copy support with memo dict."""
465
```