0 people like it.

Complex 4 - Conjugate

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
41: 
42: 
43: 
44: 
45: 
46: 
47: 
48: 
49: 
// Define complex type with some operators
type Complex =
    { Re : float;
      Im : float }
    static member (+) (z1, z2) = 
        { Re = z1.Re + z2.Re; 
          Im = z1.Im + z2.Im }
    static member (-) (z1, z2) = 
        { Re = z1.Re - z2.Re; 
          Im = z1.Im - z2.Im }
    static member (*) (z1, z2) = 
        { Re = ((z1.Re * z2.Re) - (z1.Im * z2.Im));
          Im = ((z1.Re * z2.Im) + (z1.Im * z2.Re)) }
    static member (/) (z1, z2) = 
        let z2_conj = {Re = z2.Re; Im = -z2.Im}
        let den = (z2 * z2_conj).Re
        let num = z1 * z2_conj
        { Re = num.Re / den;
          Im = num.Im / den }
    static member (~-) z = 
        { Re = -z.Re; 
          Im = -z.Im };;

// .. and printing
let print z = printfn "%.3f%+.3fi" z.Re z.Im;;

// .. and the conjugate
let conj z = 
    { Re = z.Re; 
      Im = -z.Im };;

// Problem 1.1
let z = {Re = 4.0; Im = 3.0};;
let w = {Re = 2.0; Im = -5.0};;
let one = {Re = 1.0; Im = 0.0 };;

print (one / z);;

// Check those fractions
printfn "%f %f" (4.0 / 25.0) (3.0 / 25.0);;

print (z * (conj w));;

print ((conj z) * w);;

print ((conj z) / (conj w));;

// Check those fractions
printfn "%f %f" (4.0 / 25.0) (3.0 / 25.0);;
Complex.Re: float
Multiple items
val float : value:'T -> float (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.float

--------------------
type float = System.Double

Full name: Microsoft.FSharp.Core.float

--------------------
type float<'Measure> = float

Full name: Microsoft.FSharp.Core.float<_>
Complex.Im: float
val z1 : Complex
val z2 : Complex
val z2_conj : Complex
val den : float
val num : Complex
val z : Complex
val print : z:Complex -> unit

Full name: Script.print
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
val conj : z:Complex -> Complex

Full name: Script.conj
val z : Complex

Full name: Script.z
val w : Complex

Full name: Script.w
val one : Complex

Full name: Script.one
Raw view Test code New version

More information

Link:http://fssnip.net/6N
Posted:14 years ago
Author:
Tags: