Jump to content

Quaternion type: Difference between revisions

→‎E: new example
m (moved Simple quaternion type and operations to Quaternion type: More focused/less verbose title.)
(→‎E: new example)
Line 971:
log(exp(s)) : [1,-0.333516,-0.500275,-0.667033]
+/</lang>
 
=={{header|E}}==
 
<lang e>interface Quaternion guards QS {}
def makeQuaternion(a, b, c, d) {
return def quaternion implements QS {
to __printOn(out) {
out.print("(", a, " + ", b, "i + ")
out.print(c, "j + ", d, "k)")
}
 
# Task requirement 1
to norm() {
return (a**2 + b**2 + c**2 + d**2).sqrt()
}
 
# Task requirement 2
to negate() {
return makeQuaternion(-a, -b, -c, -d)
}
# Task requirement 3
to conjugate() {
return makeQuaternion(a, -b, -c, -d)
}
 
# Task requirement 4, 5
# This implements q + r; r + q is deliberately prohibited by E
to add(other :any[Quaternion, int, float64]) {
switch (other) {
match q :Quaternion {
return makeQuaternion(
a+q.a(), b+q.b(), c+q.c(), d+q.d())
}
match real {
return makeQuaternion(a+real, b, c, d)
}
}
}
 
# Task requirement 6, 7
# This implements q * r; r * q is deliberately prohibited by E
to multiply(other :any[Quaternion, int, float64]) {
switch (other) {
match q :Quaternion {
return makeQuaternion(
a*q.a() - b*q.b() - c*q.c() - d*q.d(),
a*q.b() + b*q.a() + c*q.d() - d*q.c(),
a*q.c() - b*q.d() + c*q.a() + d*q.b(),
a*q.d() + b*q.c() - c*q.b() + d*q.a())
}
match real {
return makeQuaternion(real*a, real*b, real*c, real*d)
}
}
}
to a() { return a }
to b() { return b }
to c() { return c }
to d() { return d }
}
}</lang>
 
<lang e>? def q1 := makeQuaternion(2,3,4,5)
# value: (2 + 3i + 4j + 5k)
 
? def q2 := makeQuaternion(3,4,5,6)
# value: (3 + 4i + 5j + 6k)
 
? q1+q2
# value: (5 + 7i + 9j + 11k)
 
? q1*q2
# value: (-56 + 16i + 24j + 26k)
 
? q2*q1
# value: (-56 + 18i + 20j + 28k)
 
? q1+(-2)
# value: (0 + 3i + 4j + 5k)</lang>
 
=={{header|Forth}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.