Conjugate transpose: Difference between revisions
Content added Content deleted
(Added Sidef) |
(→{{header|Kotlin}}: Updated example see https://github.com/dkandalov/rosettacode-kotlin for details) |
||
Line 1,213: | Line 1,213: | ||
operator fun plus(other: Complex) = |
operator fun plus(other: Complex) = |
||
Complex(this.real + other.real, this.imag + other.imag) |
Complex(this.real + other.real, this.imag + other.imag) |
||
operator fun times(other: Complex) = |
operator fun times(other: Complex) = |
||
Complex(this.real * other.real - this.imag * other.imag, |
Complex(this.real * other.real - this.imag * other.imag, |
||
Line 1,221: | Line 1,221: | ||
/* tolerable equality allowing for rounding of Doubles */ |
/* tolerable equality allowing for rounding of Doubles */ |
||
infix fun teq(other: Complex) = |
infix fun teq(other: Complex) = |
||
Math.abs(this.real - other.real) <= 1e-14 && |
Math.abs(this.real - other.real) <= 1e-14 && |
||
Math.abs(this.imag - other.imag) <= 1e-14 |
Math.abs(this.imag - other.imag) <= 1e-14 |
||
override fun toString() = "${"%.3f".format(real)} " + when { |
override fun toString() = "${"%.3f".format(real)} " + when { |
||
imag > 0.0 -> "+ ${"%.3f".format(imag)}i" |
imag > 0.0 -> "+ ${"%.3f".format(imag)}i" |
||
imag == 0.0 -> "+ 0.000i" |
imag == 0.0 -> "+ 0.000i" |
||
else -> "- ${"%.3f".format(-imag)}i" |
else -> "- ${"%.3f".format(-imag)}i" |
||
} |
} |
||
Line 1,235: | Line 1,235: | ||
val rows = this.size |
val rows = this.size |
||
val cols = this[0].size |
val cols = this[0].size |
||
return Matrix(cols) { i -> Vector(rows) { j -> this[j][i].conj() } } |
|||
return trans |
|||
} |
} |
||
Line 1,270: | Line 1,269: | ||
val ct = this.conjTranspose() |
val ct = this.conjTranspose() |
||
return (this * ct) teq (ct * this) |
return (this * ct) teq (ct * this) |
||
} |
} |
||
fun Matrix.isUnitary(): Boolean { |
fun Matrix.isUnitary(): Boolean { |
||
Line 1,276: | Line 1,275: | ||
val prod = this * ct |
val prod = this * ct |
||
val ident = identityMatrix(prod.size) |
val ident = identityMatrix(prod.size) |
||
val prod2 = ct * this |
val prod2 = ct * this |
||
return (prod teq ident) && (prod2 teq ident) |
return (prod teq ident) && (prod2 teq ident) |
||
} |
} |
||
fun Matrix.print() { |
fun Matrix.print() { |
||
val rows = this.size |
val rows = this.size |
||
Line 1,293: | Line 1,292: | ||
fun identityMatrix(n: Int): Matrix { |
fun identityMatrix(n: Int): Matrix { |
||
require(n >= 1) |
require(n >= 1) |
||
val ident = Matrix(n) { Vector(n) { C(0.0, 0.0) } } |
val ident = Matrix(n) { Vector(n) { C(0.0, 0.0) } } |
||
for (i in 0 until n) ident[i][i] = C(1.0, 0.0) |
for (i in 0 until n) ident[i][i] = C(1.0, 0.0) |
||
return ident |
return ident |
||
} |
} |
||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |