microsoft/qdk
Publicmirrored fromhttps://github.com/microsoft/qdkAvailable
library/signed/src/Measurement.qs
50lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | import Std.Diagnostics.Fact; |
| 5 | import Operations.Invert2sSI; |
| 6 | |
| 7 | /// # Summary |
| 8 | /// Measures a signed integer of a given width. |
| 9 | /// If the width is 4, the qubit register will be measured as a 4-bit signed integer. |
| 10 | /// This means that bit n is the sign bit, and bits n-1 to 0 are the integer value. |
| 11 | /// If fewer than `width` qubits are provided, the remaining bits are assumed to be 0. |
| 12 | /// For example, if qubit register `[q1, q2, q3]` is passed in, but the width is 5, |
| 13 | /// the integer value will be measured as `[0, 0, q1, q2, q3]`, with the first 0 being |
| 14 | /// the sign bit (positive). This is in contrast to the standard library `MeasureInteger`, |
| 15 | /// which always measures unsigned integers up to and including 63 qubits in width. |
| 16 | /// If the length of the qubit register passed in is greater than the width, this operation |
| 17 | /// will throw an error. |
| 18 | /// |
| 19 | /// # Input |
| 20 | /// ## target |
| 21 | /// A qubit register representing the signed integer to be measured. |
| 22 | /// |
| 23 | /// ## width |
| 24 | /// The width of the signed integer to be measured. |
| 25 | operation MeasureSignedInteger(target : Qubit[], width : Int) : Int { |
| 26 | let nBits = Length(target); |
| 27 | Fact(nBits <= 64, $"`Length(target)` must be less than or equal to 64, but was {nBits}."); |
| 28 | Fact(nBits <= width, $"`Length(target)` must be less than or equal to `width`, but was {nBits}."); |
| 29 | Fact(nBits > 0, $"`width` must be greater than 0, but was {width}."); |
| 30 | |
| 31 | mutable coefficient = 1; |
| 32 | let signBit = MResetZ(target[nBits - 1]); |
| 33 | if (signBit == One) { |
| 34 | Operations.Invert2sSI(target); |
| 35 | set coefficient = -1; |
| 36 | } |
| 37 | |
| 38 | mutable number = 0; |
| 39 | for i in 0..nBits - 2 { |
| 40 | if (MResetZ(target[i]) == One) { |
| 41 | set number |||= 1 <<< i; |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | ResetAll(target); |
| 46 | |
| 47 | number * coefficient |
| 48 | } |
| 49 | |
| 50 | export MeasureSignedInteger; |
| 51 | |