MCPcopy Create free account
hub / github.com/RcppCore/Rcpp / Normalize

Function Normalize

inst/include/Rcpp/sugar/functions/sample.h:57–77  ·  view source on GitHub ↗

Adapted from `FixupProb` Normalizes a probability vector 'p' S.T. sum(p) == 1

Source from the content-addressed store, hash-verified

55// Adapted from `FixupProb`
56// Normalizes a probability vector 'p' S.T. sum(p) == 1
57inline void Normalize(Vector<REALSXP>& p, int require_k, bool replace)
58{
59 double sum = 0.0;
60 R_xlen_t npos = 0, i = 0, n = p.size();
61
62 for ( ; i < n; i++) {
63 if (!R_FINITE(p[i]) || (p[i] < 0)) {
64 stop("Probabilities must be finite and non-negative!");
65 }
66 npos += (p[i] > 0.0);
67 sum += p[i];
68 }
69
70 if ((!npos) || (!replace && (require_k > npos))) {
71 stop("Too few positive probabilities!");
72 }
73
74 for (i = 0; i < n; i++) {
75 p[i] /= sum;
76 }
77}
78
79// Adapted from `ProbSampleReplace`
80// Index version

Callers 1

sampleFunction · 0.85

Calls 2

stopFunction · 0.85
sizeMethod · 0.45

Tested by

no test coverage detected