microsoft/qdk
Publicmirrored from https://github.com/microsoft/qdkAvailable
katas/content/random_numbers/weighted_random_bit/solution.qs
26lines · modecode
| 1 | namespace Kata { |
| 2 | open Microsoft.Quantum.Math; |
| 3 | |
| 4 | operation WeightedRandomBit(x : Double) : Int { |
| 5 | // Calculate theta value. |
| 6 | let theta = 2.0 * ArcCos(Sqrt(x)); // (or) 2.0 * ArcSin(Sqrt(1.0 - x)); |
| 7 | |
| 8 | // Allocate single qubit. |
| 9 | use q = Qubit(); |
| 10 | |
| 11 | // Set qubit in superposition state which aligns with given probabilities. |
| 12 | Ry(theta, q); |
| 13 | |
| 14 | |
| 15 | // Measuring state of qubit and reset. |
| 16 | let result = M(q); |
| 17 | Reset(q); |
| 18 | |
| 19 | // Reset qubit and return integer value of result. |
| 20 | if result == One { |
| 21 | return 1; |
| 22 | } |
| 23 | return 0; |
| 24 | } |
| 25 | |
| 26 | } |
| 27 | |