Arithmetic/Complex: Difference between revisions
Content added Content deleted
(Restoring visibility of <math> tag content hidden by under-tested cosmetic edit at 01:25, 25 August 2016) |
(Added Kotlin) |
||
Line 2,383: | Line 2,383: | ||
julia> imag(z1) |
julia> imag(z1) |
||
3.0</lang> |
3.0</lang> |
||
=={{header|Kotlin}}== |
|||
<lang scala>// version 1.0.5-2 |
|||
class Complex(val real: Double, val imag: Double) { |
|||
operator fun plus(other: Complex): Complex { |
|||
return Complex(this.real + other.real, this.imag + other.imag) |
|||
} |
|||
operator fun times(other: Complex): Complex { |
|||
return Complex(this.real * other.real - this.imag * other.imag, |
|||
this.real * other.imag + this.imag * other.real) |
|||
} |
|||
fun inv(): Complex { |
|||
val denom : Double = this.real * this.real + this.imag * this.imag |
|||
return Complex(this.real / denom, -this.imag / denom) |
|||
} |
|||
operator fun unaryMinus() : Complex { |
|||
return Complex(-this.real, -this.imag) |
|||
} |
|||
operator fun minus(other: Complex): Complex { |
|||
return this + (-other) |
|||
} |
|||
operator fun div(other: Complex): Complex { |
|||
return this * other.inv() |
|||
} |
|||
fun conj(): Complex { |
|||
return Complex(this.real, -this.imag) |
|||
} |
|||
override fun toString(): String { |
|||
if (this.imag >= 0.0) |
|||
return "${this.real} + ${this.imag}i" |
|||
else |
|||
return "${this.real} - ${-this.imag}i" |
|||
} |
|||
} |
|||
fun main(args: Array<String>) { |
|||
val x = Complex(1.0, 3.0) |
|||
val y = Complex(5.0, 2.0) |
|||
println("x = $x") |
|||
println("y = $y") |
|||
println("x + y = ${x + y}") |
|||
println("x - y = ${x - y}") |
|||
println("x * y = ${x * y}") |
|||
println("x / y = ${x / y}") |
|||
println("-x = ${-x}") |
|||
println("1 / x = ${x.inv()}") |
|||
println("x* = ${x.conj()}") |
|||
}</lang> |
|||
{{out}} |
|||
<pre> |
|||
x = 1.0 + 3.0i |
|||
y = 5.0 + 2.0i |
|||
x + y = 6.0 + 5.0i |
|||
x - y = -4.0 + 1.0i |
|||
x * y = -1.0 + 17.0i |
|||
x / y = 0.3793103448275862 + 0.4482758620689655i |
|||
-x = -1.0 - 3.0i |
|||
1 / x = 0.1 - 0.3i |
|||
x* = 1.0 - 3.0i |
|||
</pre> |
|||
=={{header|LFE}}== |
=={{header|LFE}}== |