microsoft/qdk
Publicmirrored from https://github.com/microsoft/qdkAvailable
katas/content/distinguishing_unitaries/rz_ry/Solution.qs
38lines · modecode
| 1 | namespace Kata { |
| 2 | open Microsoft.Quantum.Convert; |
| 3 | open Microsoft.Quantum.Math; |
| 4 | |
| 5 | function ComputeRepetitions(angle : Double, offset : Int, accuracy : Double) : Int { |
| 6 | mutable pifactor = 0; |
| 7 | while (true) { |
| 8 | let pimultiple = PI() * IntAsDouble(2 * pifactor + offset); |
| 9 | let times = Round(pimultiple / angle); |
| 10 | if AbsD(pimultiple - (IntAsDouble(times) * angle)) / PI() < accuracy { |
| 11 | return times; |
| 12 | } |
| 13 | set pifactor += 1; |
| 14 | } |
| 15 | return 0; |
| 16 | } |
| 17 | |
| 18 | operation DistinguishRzFromRy (theta : Double, unitary : (Qubit => Unit is Adj+Ctl)) : Int { |
| 19 | use q = Qubit(); |
| 20 | let times = ComputeRepetitions(theta, 1, 0.1); |
| 21 | mutable attempt = 1; |
| 22 | mutable measuredOne = false; |
| 23 | repeat { |
| 24 | for _ in 1 .. times { |
| 25 | unitary(q); |
| 26 | } |
| 27 | // for Rz, we'll never venture away from |0⟩ state, so as soon as we got |1⟩ we know it's not Rz |
| 28 | if MResetZ(q) == One { |
| 29 | set measuredOne = true; |
| 30 | } |
| 31 | // if we try several times and still only get |0⟩s, chances are that it is Rz |
| 32 | } until (attempt == 4 or measuredOne) |
| 33 | fixup { |
| 34 | set attempt += 1; |
| 35 | } |
| 36 | return measuredOne ? 1 | 0; |
| 37 | } |
| 38 | } |
| 39 | |