Quaternion type: Difference between revisions

Content added Content deleted
Line 1,478: Line 1,478:


=={{header|Crystal}}==
=={{header|Crystal}}==
{{trans|Rust:Ruby}}

<lang ruby>class Quaternion
<lang ruby>class Quaternion
property a, b, c, d
property a, b, c, d


def initialize(@a : Int64, @b : Int64, @c : Int64, @d : Int64) end
def initialize(@a : Int64, @b : Int64, @c : Int64, @d : Int64) end


def norm; Math.sqrt(self.a**2 + self.b**2 + self.c**2 + self.d**2) end
def norm; Math.sqrt(a**2 + b**2 + c**2 + d**2) end
def conj; Quaternion.new(self.a, -self.b, -self.c, -self.d) end
def conj; Quaternion.new(a, -b, -c, -d) end
def +(n) Quaternion.new(a + n, b, c, d) end
def +(rhs : Quaternion)
def +(rhs : Quaternion)
Quaternion.new(self.a + rhs.a, self.b + rhs.b, self.c + rhs.c, self.d + rhs.d)
Quaternion.new(a + rhs.a, b + rhs.b, c + rhs.c, d + rhs.d)
end
def +(rhs : Int32 | Int64)
Quaternion.new(self.a + rhs, self.b, self.c, self.d)
end
end


def -(rhs : Quaternion)
def -(rhs : Quaternion)
Quaternion.new(self.a - rhs.a, self.b - rhs.b, self.c - rhs.c, self.d - rhs.d)
Quaternion.new(a - rhs.a, b - rhs.b, c - rhs.c, d - rhs.d)
end
end


def *(rhs : Quaternion)
def *(rhs : Quaternion)
Quaternion.new(
Quaternion.new(
self.a * rhs.a - self.b * rhs.b - self.c * rhs.c - self.d * rhs.d,
a * rhs.a - b * rhs.b - c * rhs.c - d * rhs.d,
self.a * rhs.b + self.b * rhs.a + self.c * rhs.d - self.d * rhs.c,
a * rhs.b + b * rhs.a + c * rhs.d - d * rhs.c,
self.a * rhs.c - self.b * rhs.d + self.c * rhs.a + self.d * rhs.b,
a * rhs.c - b * rhs.d + c * rhs.a + d * rhs.b,
self.a * rhs.d + self.b * rhs.c - self.c * rhs.b + self.d * rhs.a)
a * rhs.d + b * rhs.c - c * rhs.b + d * rhs.a)
end
end


def *(n) Quaternion.new(a * n, b * n, c * n, d * n) end
def *(rhs : Int32 | Int64)
Quaternion.new(self.a * rhs, self.b * rhs, self.c * rhs, self.d * rhs)
def -() Quaternion.new(-a, -b, -c, -d) end
def ==(rhs : Quaternion) self.to_s == rhs.to_s end
end
def to_s() "(#{a} #{sgn(b)}i #{sgn(c)}j #{sgn(d)}k)\n" end

private def sgn(n) n.sign|1 == 1 ? "+ #{n}" : "- #{n.abs}" end
def -()
Quaternion.new(-self.a, -self.b, -self.c, -self.d)
end

def ==(rhs : Quaternion)
self.to_s == rhs.to_s
end

def to_s
"(#{self.a} #{sgn(self.b)}i #{sgn(self.c)}j #{sgn(self.d)}k)\n"
end

private def sgn(n)
n.sign == 1 ? "+ #{n}" : "- #{n.abs}"
end
end
end


Line 1,586: Line 1,570:
-q0 = (-1 - 2i - 3j - 4k)
-q0 = (-1 - 2i - 3j - 4k)
conjugate of q0 = (1 - 2i - 3j - 4k)
conjugate of q0 = (1 - 2i - 3j - 4k)
q0 * (conjugate of q0) = (30 - 0i - 0j - 0k)
q0 * (conjugate of q0) = (30 + 0i + 0j + 0k)
(conjugate of q0) * q0 = (30 - 0i - 0j - 0k)
(conjugate of q0) * q0 = (30 + 0i + 0j + 0k)


r + q0 = (8 + 2i + 3j + 4k)
r + q0 = (8 + 2i + 3j + 4k)