Jon - 1 year ago 52

C++ Question

I am trying to evaluate a statistics problem via a Monte Carlo method. In this problem I am generating a random number and comparing it to a fixed probability number stored in a vector array titled

`comms_reliability`

for each possible scenario. In this implementation I have to copy the same lines of code multiple times, and it also limits the

`commms_reliability`

`int main(int argc, const char * argv[]) {`

int sample_size = 1000000;

std::vector<float> comms_reliability = {0.6,0.6};

float tally = 0.0;

// rang() = random number generator

// if statement for comms_reliability array of size 1

if (comms_reliability.size() == 1) {

for (int i = 0; i < sample_size; i++){

if (rang() > comms_reliability[0]) tally = tally + 1.0;

}

}

// if statement 2 for comms_reliability array of size 2

if (comms_reliability.size() == 2) {

for (int i = 0; i < sample_size; i++){

if (rang() > comms_reliability[0] && rang() > comms_reliability[1]) tally = tally + 1.0;

}

}

// if statement 3 for comms_reliability array of size 3

if (comms_reliability.size() == 3) {

for (int i = 0; i < sample_size; i++){

if (rang() > comms_reliability[0] && rang() > comms_reliability[1] &&

rang() > comms_reliability[2]) tally = tally + 1.0;

}

}

Answer Source

If I understand you correctly you want to make sure that all elements of `comms_reliability`

satisfy some criterion (namely being less than `rang()`

) for each sample.

So make a loop over all elements and test each, or just use `std::all_of`

:

```
// Lambda function used to test a single comm_reliability
auto is_reliable = [] (float r) { return rang() > r; };
// Iterate over your samples
for (int i = 0; i < sample_size; ++i) {
// If all elements satisfy your criterion ...
if (std::all_of(std::begin(comms_reliability),
std::end(comms_reliability),
is_reliable)) {
// .. perform your action
tally += 1.0;
}
}
```

Instead of the lambda function you could also use a normal function defined somewhere before:

```
bool is_reliable(float r) {
return rang() > r;
}
```

Note: Try to improve your variable/function naming.