Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- open System
- open System.Numerics
- open MathNet.Numerics
- open MathNet.Numerics.LinearAlgebra
- type Qregister =
- Qregister of Matrix<Complex>
- member this.measure () =
- let asArray =
- match this with
- | (Qregister x) -> x.ToColumnMajorArray ()
- let probs =
- Array.map (fun x -> x ** 2.0) asArray
- |> List.ofArray
- |> List.map (fun x -> x.Real)
- let diceRoll =
- let r = new Random () in
- r.NextDouble ()
- let makeCumulativeProbs xs (a : float) =
- let support = function
- | [] -> []
- | (head::tail) -> (head+a)::head::tail
- support xs
- let selectelem (ready, last) (a) =
- if ready then (ready, last)
- else
- if diceRoll < a then
- (true, a)
- else
- (false, a)
- let cumulativeProbs =
- probs
- |> List.fold makeCumulativeProbs [0.0]
- |> List.rev
- |> (fun x -> x.Tail)
- cumulativeProbs
- |> List.fold selectelem (false, 0.0)
- |> (fun (_, x) -> List.findIndex ((=) x) cumulativeProbs)
- let qreg n =
- let ket = matrix [[Complex (1.0, 0.0)]
- [Complex (0.0, 0.0)]]
- let rec support = function
- | 1 -> ket
- | n when n > 0 -> ket.KroneckerProduct (support (n-1))
- | _ -> failwith "degree must be greater than 0"
- Qregister (support n)
- type Gate =
- Gate of Matrix<Complex>
- static member (*) (Gate a, Gate b) = Gate (a.KroneckerProduct b)
- static member (+) (a, b) = Binding [a; b]
- static member (+) (a, b) = a + (Binding [b])
- static member (+) (a, b) = (Binding [a]) + b
- static member apply (Gate a) (Qregister s) = Qregister (a * s)
- static member (?-) (state : Qregister, gate : Gate) =
- Gate.apply gate state
- and Binding =
- Binding of List<Gate>
- static member (+) (Binding a, Binding b) = Binding (List.append a b)
- static member (?-) (state, binding) =
- match binding with
- | Binding [] -> state
- | Binding (head::tail) ->
- (Gate.apply head state) ?- (Binding tail)
- // lol
- let I = matrix [[ Complex (1.0, 0.0); Complex (0.0, 0.0) ]
- [ Complex (0.0, 0.0); Complex (1.0, 0.0) ]] |> Gate
- let H = (Complex (1.0/sqrt 2.0, 0.0)) *
- matrix [[ Complex (1.0, 0.0); Complex (1.0, 0.0)]
- [ Complex (1.0, 0.0); Complex (-1.0, 0.0)]] |> Gate
- let X = matrix [[Complex (0.0, 0.0); Complex (0.0, -1.0)]
- [Complex (0.0, 1.0); Complex (0.0, 0.0)]] |> Gate
- let CNOT =
- let unit = Complex (1.0, 0.0)
- let zero = Complex (0.0, 0.0)
- matrix [[unit; zero; zero; zero]
- [zero; unit; zero; zero]
- [zero; zero; zero; unit]
- [zero; zero; unit; zero]] |> Gate
- (qreg 2) ?- (H * H + CNOT + I * H)
- |> (fun x -> x.measure ())
- |> printfn "%A"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement