-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
create function to generate random numbers from 50 to 100 (#1)
Co-authored-by: Irina Kogai <[email protected]>
- Loading branch information
1 parent
f5e361b
commit fb5ef31
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
58 changes: 58 additions & 0 deletions
58
1_RandomNumberGeneratorMinMax/1_RandomNumberGeneratorMinMax.qs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
namespace QuantumRandomNumberGenerator { | ||
open Microsoft.Quantum.Convert; | ||
open Microsoft.Quantum.Intrinsic; | ||
open Microsoft.Quantum.Math; | ||
|
||
@EntryPoint() | ||
operation Main() : Int { | ||
let min = 50; | ||
let max = 100; | ||
Message($"Sampling a random number between {min} and {max}: "); | ||
|
||
return GenerateRandomNumberInRange(min, max); | ||
} | ||
|
||
operation GenerateRandomNumberInRange(min : Int, max : Int) : Int { | ||
// Generate a random number in the 0..(max - min) range. | ||
let sample = GenerateRandomNumber(max - min); | ||
|
||
// Shift the random number to the min..max range. | ||
return sample + min; | ||
} | ||
|
||
/// Generates a random number between 0 and `max`. | ||
operation GenerateRandomNumber(max : Int) : Int { | ||
// Determine the number of bits needed to represent `max` and store it | ||
// in the `nBits` variable. | ||
let nBits = BitSizeI(max); | ||
|
||
// Then generate `nBits` random bits which will | ||
// represent the generated random number. | ||
mutable bits = []; | ||
for idxBit in 1..nBits { | ||
set bits += [GenerateRandomBit()]; | ||
} | ||
let sample = ResultArrayAsInt(bits); | ||
|
||
// Return random number if it is within the requested range. | ||
// Generate it again if it is outside the range. | ||
return sample > max ? GenerateRandomNumber(max) | sample; | ||
} | ||
|
||
operation GenerateRandomBit() : Result { | ||
// Allocate a qubit, by default it is in zero state | ||
use q = Qubit(); | ||
|
||
// We apply a Hadamard operation H to the state | ||
// It now has a 50% chance of being measured 0 or 1 | ||
H(q); | ||
|
||
// Now we measure the qubit in Z-basis. | ||
let result = M(q); | ||
|
||
// Reset the qubit so it can be safely released. | ||
Reset(q); | ||
|
||
return result; | ||
} | ||
} |