Let's say there is a certain program simulating tossing a coin. It is necessary to make it so that in 95 cases of tossing a coin from one hundred an eagle, and not tails, fell out. How can this be achieved?
- 7Why are C ++ 11 tagged? Do you think this daunting task can be solved only with the involvement of the latest C ++ standard? - DreamChild
- Of course, just like that - PaulD
- oneStroustrup would probably choke upon learning about it - DreamChild
- Well, sorry for him - PaulD
- one@SoloMio: then use not rand, but rand. - VladD
5 answers
rand is a good solution and on large volumes of data it will give a fairly even distribution. But not very large will be a small variation (a few percent). If you need a 100% guarantee that there will be a correct probability, then you need to use a different approach. See my example, if your compiler does not support the latter standard, then just look at how shuffle is implemented.
#include <iostream> #include <algorithm> #include <random> #include <chrono> using namespace std; int main() { vector<int> a(100); // массив на 100 бросков fill_n(a.begin(), 95, 1); // 1 - это орлы fill_n(a.begin() + 95, 5, 0); // 0 - это решки // теперь магия. получаем сид и перемешиваем массив unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); shuffle(a.begin(), a.end(), std::default_random_engine(seed)); // делаем подсчет int orel = count_if (a.begin(), a.end(), [](int i){return (i==1);} ); int reshka = count_if (a.begin(), a.end(), [](int i){return (i==0);} ); // выведем соотношение cout << "орлов/решек " << orel << "/" << reshka << endl; // выведем набор for_each (a.begin(), a.end(), [](int i) {cout << i << " ";}); cout << endl; return 0; }
- Thank you, exactly what was needed - PaulD
- <small_prikyrki> probability is just right in the case of a simple rand. the probability that exactly 95 eagles will fall out of 100 shots is exactly
C^5_100/2^100 = 75287520 / 1267650600228229401496703205376 ~= 6*10^{-23}
</ minor_prime> - and we need it? that was not the problem. - KoVadim
- @KoVadim: Yes, I agree, the calculations are wrong, because they are repelled by equal probabilities of falling of an eagle and tails, which is not a priori. But: your sequence is not random! For example, if you first dropped 5 tails in a row, then 95 eagles will fall further, which is not the case in the case of a coin: the probability of a falling eagle has no right to depend on previous results. - VladD 5:41 pm
- Your reasoning has nothing to do with the task. - KoVadim pm
Generate a random number. From one to one hundred. Then you write: if the number is less than 95, then the eagle, otherwise tails. So there will be a probability of 0.95
- if the distribution is uniform, if not, then we will have an eagle in a much smaller quantity than necessary. - PaulD 2:58 pm
- random number and implies that any number will fall out with the same probability. - sinedsem
- 6mom klyanus! - sinedsem
- 3> Haha, how ridiculous, my dear, and why such a dumb-billed seriousness? You were given the most obvious answer to a more than elementary question, and you turn up your nose. I would like to thank the respondents. Do not like the algorithm for generating random numbers in C ++? Write your own with blackjack and young ladies, probably it will be much better than those already implemented in the language - DreamChild
- 2Thank you, thank you, but why, when giving an answer, to sarcast and something else to do there? Well, the answer would be simple: "the Rand () function returns a number according to the uniform probability distribution law," and no problems. Why this sarcasm, "swear mother"? I need this information for writing a test task, this is a casino application. And if in the end the distribution is not even, but exponential for example, someone will lose a lot of money. It is not difficult to guess who will be bad after that. - PaulD
Let's remember the mathematics of the school course for the 5th grade :) Topic: "correct fractions".
95 из 100( вероятность выпадения орла --- 95/100 ) => 95/100 = 19/20 => вам нужно подбирать число в диапазоне от 1 до 20 : srand(time(NULL)); int res = rand()%20+1; cout<<res<<endl; if(res==20) cout<<"Решка!"; else cout<<"Орел!"; cout<<endl;
- so essentially what I suggested. Naturally, the best will be to reduce. - sinedsem
- Not optimal - or rather. When generating numbers from 1 to 100, the probability of generating numbers from 95 to 100 may be somewhat less. This can be caused by the fact that the processor generates pseudo-random numbers in accordance with the specified "grain". Correct someone if I'm wrong. - AseN 3:49 PM
- start such code and see #include <iostream> #include <cstdlib> using namespace std; int main () {const int range = 10000; int q = 0; for (int i = 0; i <range; i ++) {int t = rand ()% 100; if (t> = 95) q ++; } cout << q * 100.0 / range << endl; return 0; } Only at 100000-1000000 attempts, the percentage becomes correct. - KoVadim
- @KoVadim: according to this logic, for a probability of 0.5 is it necessary that the tails and eagles are always alternately generated? - VladD
- onein the case of 1/2, the reservoir may be two, but not necessarily. >> the sequence with the tank is not accidental: you can always predict what the last result in the tank will be logical. But this will be known only when all previous elements are analyzed. I will give a counterexample. Imagine a deck of cards. If you shuffle it, then the cards will be there in a random order, but after everyone except the last is removed, you can always predict the last card. But from this it will not become less random. It's like a Schrödinger cat. - KoVadim 5:46 pm
If you need a guaranteed 95% eagle, then you need to make a list of, for example, 100 (you need to know exactly the number of throws), 5 of any (let's say first) make true, the rest are false, and then randomly pull them out of the list one at a time so that they do not repeat, that by the end of the list, the ratio stopro will be 95/5
The topic is of course old, but no one suggested that with ++ 11 way. Therefore, the rights of enlightenment of the masses:
// bernoulli_distribution #include <iostream> #include <random> int main() { const int nrolls=10000; std::default_random_engine generator; std::bernoulli_distribution distribution(0.95); int count=0; // count number of trues for (int i=0; i<nrolls; ++i) if (distribution(generator)) ++count; std::cout << "bernoulli_distribution (0.95) x 10000:" << std::endl; std::cout << "true: " << count << std::endl; std::cout << "false: " << nrolls-count << std::endl; return 0; }