Probability generator (generate uniform and non-uniform 0, 1)

Source: Internet
Author: User

Programs that generate a probability of 0 and 1 can be adjusted according to the settings:

#include <stdio.h>#include <stdlib.h>int EqualProbability() {  if (rand() % 2 == 0) {    return 0;  } else {    return 1;  }}int BiasProbability(int parameter) {  int size = parameter + 1;  if (rand() % size == 0) {    return 0;  } else {    return 1;  }}int main(int argc, char** argv) {  int zero_counter = 0;  int one_counter = 0;  const int kGenerateTime = 1000000;  for (int i = 0; i < kGenerateTime; ++i) {    if (EqualProbability() == 0) {      zero_counter++;    } else {      one_counter++;    }  }  printf("zero:%d one:%d\n", zero_counter, one_counter);  zero_counter = 0;  one_counter = 0;  for (int i = 0; i < kGenerateTime; ++i) {    if (BiasProbability(10) == 0) {      zero_counter++;    } else {      one_counter++;    }  }  printf("zero:%d one:%d\n", zero_counter, one_counter);}

Related questions:

Known as a random generator, the probability of generating 0 is P, and the probability of generating 1 is 1-P. Now you need to construct a generator,
So that the probability of constructing 0 and 1 is 1/2. Construct a generator so that the probability of constructing 1, 2, and 3 is 1/3 ;...,
Construct a generator so that the probability of constructing 1, 2, 3,... n is 1/N, requiring the lowest complexity.

For n = 2, 01 indicates 0, 10 indicates 1, and other probabilities. In other cases, discard

For n = 3, 001 indicates 1, 010 indicates 2,100 indicates 3, and other probabilities.

For N = 4, think 0001 represents 1, 0010 represents 2, 0100 represents 3, represents 4, and other probability, other circumstances give up

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.