RosettaCodeData/Task/Arithmetic-Complex/Nanoquery/arithmetic-complex.nanoquery

57 lines
1.4 KiB
Plaintext

import math
class Complex
declare real
declare imag
def Complex()
real = 0.0
imag = 0.0
end
def Complex(r, i)
real = double(r)
imag = double(i)
end
def operator-(b)
return new(Complex, this.real - b.real, this.imag - b.imag)
end
def operator+(b)
return new(Complex, this.real + b.real, this.imag + b.imag)
end
def operator*(b)
// FOIL of (a+bi)(c+di) with i*i = -1
return new(Complex, this.real * b.real - this.imag * b.imag,\
this.real * b.imag + this.imag * b.real)
end
def inv()
// 1/(a+bi) * (a-bi)/(a-bi) = 1/(a+bi) but it's more workable
denom = this.real * this.real + this.imag * this.imag
return new(Complex, real/denom, -imag/denom)
end
def neg()
return new(Complex, -this.real, -this.imag)
end
def conj()
return new(Complex, this.real, -this.imag)
end
def toString()
return this.real + " + " + this.imag + " * i"
end
end
a = new(Complex, math.pi, -5)
b = new(Complex, -1, 2.5)
println a.neg()
println a + b
println a.inv()
println a * b
println a.conj()