Arithmetic/Complex: Difference between revisions
Content added Content deleted
No edit summary |
|||
Line 1,800: | Line 1,800: | ||
1 / z1 = 0.15 - 0.09 i |
1 / z1 = 0.15 - 0.09 i |
||
- z1 = -5.00 - 3.00 i</pre> |
- z1 = -5.00 - 3.00 i</pre> |
||
=={{header|Oberon-2}}== |
|||
Oxford Oberon Compiler |
|||
<lang oberon2> |
|||
MODULE Complex; |
|||
IMPORT Files,Out; |
|||
TYPE |
|||
Complex* = POINTER TO ComplexDesc; |
|||
ComplexDesc = RECORD |
|||
r-,i-: REAL; |
|||
END; |
|||
PROCEDURE (CONST x: Complex) Add*(CONST y: Complex): Complex; |
|||
BEGIN |
|||
RETURN New(x.r + y.r,x.i + y.i) |
|||
END Add; |
|||
PROCEDURE (CONST x: Complex) Sub*(CONST y: Complex): Complex; |
|||
BEGIN |
|||
RETURN New(x.r - y.r,x.i - y.i) |
|||
END Sub; |
|||
PROCEDURE (CONST x: Complex) Mul*(CONST y: Complex): Complex; |
|||
BEGIN |
|||
RETURN New(x.r*y.r - x.i*y.i,x.r*y.i + x.i*y.r) |
|||
END Mul; |
|||
PROCEDURE (CONST x: Complex) Div*(CONST y: Complex): Complex; |
|||
VAR |
|||
d: REAL; |
|||
BEGIN |
|||
d := y.r * y.r + y.i * y.i; |
|||
RETURN New((x.r*y.r + x.i*y.i)/d,(x.i*y.r - x.r*y.i)/d) |
|||
END Div; |
|||
(* Reciprocal *) |
|||
PROCEDURE (CONST x: Complex) Rec*(): Complex; |
|||
VAR |
|||
d: REAL; |
|||
BEGIN |
|||
d := x.r * x.r + y.i * y.i; |
|||
RETURN New(x.r/d,(-1.0 * x.i)/d); |
|||
END Rec; |
|||
(* Conjugate *) |
|||
PROCEDURE (x: Complex) Con*(): Complex; |
|||
BEGIN |
|||
RETURN New(x.r, (-1.0) * x.i); |
|||
END Con; |
|||
PROCEDURE (x: Complex) Out(out : Files.File); |
|||
BEGIN |
|||
Files.WriteString(out,"("); |
|||
Files.WriteReal(out,x.r); |
|||
Files.WriteString(out,","); |
|||
Files.WriteReal(out,x.i); |
|||
Files.WriteString(out,"i)") |
|||
END Out; |
|||
PROCEDURE New(x,y: REAL): Complex; |
|||
VAR |
|||
r: Complex; |
|||
BEGIN |
|||
NEW(r);r.r := x;r.i := y; |
|||
RETURN r |
|||
END New; |
|||
VAR |
|||
r,x,y: Complex; |
|||
BEGIN |
|||
x := New(1.5,3); |
|||
y := New(1.0,1.0); |
|||
Out.String("x: ");x.Out(Files.stdout);Out.Ln; |
|||
Out.String("y: ");y.Out(Files.stdout);Out.Ln; |
|||
r := x.Add(y); |
|||
Out.String("x + y: ");r.Out(Files.stdout);Out.Ln; |
|||
r := x.Sub(y); |
|||
Out.String("x - y: ");r.Out(Files.stdout);Out.Ln; |
|||
r := x.Mul(y); |
|||
Out.String("x * y: ");r.Out(Files.stdout);Out.Ln; |
|||
r := x.Div(y); |
|||
Out.String("x / y: ");r.Out(Files.stdout);Out.Ln; |
|||
r := y.Rec(); |
|||
Out.String("1 / y: ");r.Out(Files.stdout);Out.Ln; |
|||
r := x.Con(); |
|||
Out.String("x': ");r.Out(Files.stdout);Out.Ln; |
|||
END Complex. |
|||
</lang> |
|||
Output: |
|||
<pre> |
|||
x: (1.50000,3.00000i) |
|||
y: (1.00000,1.00000i) |
|||
x + y: (2.50000,4.00000i) |
|||
x - y: (0.500000,2.00000i) |
|||
x * y: (-1.50000,4.50000i) |
|||
x / y: (2.25000,0.750000i) |
|||
1 / y: (0.500000,-0.500000i) |
|||
x': (1.50000,-3.00000i) |
|||
</pre> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |