Quaternion type: Difference between revisions

no edit summary
No edit summary
Line 4,713:
</pre>
 
 
=={{header|PowerShell}}==
{{works with|PowerShell|5}}
<lang PowerShell>
class Quaternion {
[Double]$a
[Double]$b
[Double]$c
[Double]$d
Quaternion() {
$this.a = 0
$this.b = 0
$this.c = 0
$this.d = 0
}
Quaternion([Double]$a, [Double]$b, [Double]$c, [Double]$d) {
$this.a = $a
$this.b = $b
$this.c = $c
$this.d = $d
}
[Double]abs2() {return $this.a*$this.a + $this.b*$this.b + $this.c*$this.c + $this.d*$this.d}
[Double]abs() {return [math]::sqrt($this.abs2())}
static [Quaternion]real([Double]$r) {return [Quaternion]::new($r, 0, 0, 0)}
static [Quaternion]add([Quaternion]$m,[Quaternion]$n) {return [Quaternion]::new($m.a+$n.a, $m.b+$n.b, $m.c+$n.c, $m.d+$n.d)}
[Quaternion]addreal([Double]$r) {return [Quaternion]::add($this,[Quaternion]::real($r))}
static [Quaternion]mul([Quaternion]$m,[Quaternion]$n) {
return [Quaternion]::new(
($m.a*$n.a) - ($m.b*$n.b) - ($m.c*$n.c) - ($m.d*$n.d),
($m.a*$n.b) + ($m.b*$n.a) + ($m.c*$n.d) - ($m.d*$n.c),
($m.a*$n.c) - ($m.b*$n.d) + ($m.c*$n.a) + ($m.d*$n.b),
($m.a*$n.d) + ($m.b*$n.c) - ($m.c*$n.b) + ($m.d*$n.a))
}
 
[Quaternion]mul([Double]$r) {return [Quaternion]::new($r*$this.a, $r*$this.b, $r*$this.c, $r*$this.d)}
[Quaternion]negate() {return $this.mul(-1)}
[Quaternion]conjugate() {return [Quaternion]::new($this.a, -$this.b, -$this.c, -$this.d)}
static [String]st([Double]$r) {
if(0 -le $r) {return "+$r"} else {return "$r"}
}
[String]show() {return "$($this.a)$([Quaternion]::st($this.b))i$([Quaternion]::st($this.c))j$([Quaternion]::st($this.d))k"}
static [String]show([Quaternion]$other) {return $other.show()}
}
 
 
$q = [Quaternion]::new(1, 2, 3, 4)
$q1 = [Quaternion]::new(2, 3, 4, 5)
$q2 = [Quaternion]::new(3, 4, 5, 6)
$r = 7
"`$q: $($q.show())"
"`$q1: $($q1.show())"
"`$q2: $($q2.show())"
"`$r: $r"
""
"norm `$q: $($q.abs())"
"negate `$q: $($q.negate().show())"
"conjugate `$q: $($q.conjugate().show())"
"`$q + `$r: $($q.addreal($r).show())"
"`$q1 + `$q2: $([Quaternion]::show([Quaternion]::add($q1,$q2)))"
"`$q * `$r: $($q.mul($r).show())"
"`$q1 * `$q2: $([Quaternion]::show([Quaternion]::mul($q1,$q2)))"
"`$q2 * `$q1: $([Quaternion]::show([Quaternion]::mul($q2,$q1)))"
</lang>
<b>Output:</b>
<pre>
norm $q: 5.47722557505166
negate $q: -1-2i-3j-4k
conjugate $q: 1-2i-3j-4k
$q + $r: 8+2i+3j+4k
$q1 + $q2: 5+7i+9j+11k
$q * $r: 7+14i+21j+28k
$q1 * $q2: -56+16i+24j+26k
$q2 * $q1: -56+18i+20j+28k
</pre>
=={{header|Prolog}}==
<lang Prolog>% A quaternion is represented as a complex term qx/4
678

edits