QuISP
Loading...
Searching...
No Matches
UtilFunctions.h
Go to the documentation of this file.
1#include <iostream>
2#include <map>
4
7
8/*
9 Description:
10 This is a function that, given a set of labels and weights and a random number, returns a label according to the random number
11 Args:
12 std::map<Label, double> weights: weight(double) and label are a pair of values and it is a elements of std:map.
13 rand: random number(double)
14 Return:
15 It returns label probabilistically according to the weights.
16 Example:
17 weight = {{ErrorLabel::X, 0.3}, {ErrorLabel::Z, 0.4}, {ErrorLabel::Y, 0.3}}}
18 rand = 0.4
19
20 returns ErrorLabel::Z
21 */
22template <typename Label>
23Label samplingWithWeights(std::map<Label, double> weights, double rand) {
24 double sum = 0;
25 for (auto &[l, w] : weights) {
26 sum += w;
27 }
28 double ceil = 0;
29 for (auto &[l, w] : weights) {
30 ceil += w / sum;
31
32 if (rand <= ceil) {
33 return l;
34 }
35 }
36 return (--weights.end())->first;
37}
38} // namespace quisp::util_functions
Definition IRandomNumberGenerator.h:4
Definition UtilFunctions.h:5
Label samplingWithWeights(std::map< Label, double > weights, double rand)
Definition UtilFunctions.h:23