Originally posted by spudtheimpaler
I've got a rand() in there with 1's or 0's, IE yes or no, but it's giving me a fairly even playing field, i was wondering if there was any way in biasing the results so, say, it was twice as likely to be a 1 than a 0.? Cheers fo any help (or any ideas of any kind
)
Here is a quick hack of an idea.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int foo(void) /* even odds */
{
return rand() > RAND_MAX / 2;
}
int bar(void) /* twice as likely to be 1 as 0 */
{
return rand() > RAND_MAX / 3;
}
void test(int (*function)(void), int cycles)
{
int i, result[2] = {0,0};
double x,y;
for ( i = 0; i < cycles; ++i )
{
++result[function()];
}
x = result[0] * 100.0 / cycles;
y = result[1] * 100.0 / cycles;
printf("0: %d (%.2f%%), 1: %d (%.2f%%)\n", result[0], x, result[1], y);
}
int main(void)
{
srand(time(0));
test(foo, 10000);
test(bar, 10000);
return 0;
}
/* my output
0: 4979 (49.79%), 1: 5021 (50.21%)
0: 3302 (33.02%), 1: 6698 (66.98%)
*/
[edit]A different spin on the above.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int likelihood(int difficulty)
{
return rand() < RAND_MAX / (difficulty + 1);
}
void test(int (*function)(int), int n)
{
int i, result[2] = {0,0}, cycles = 1000000;
printf("likelihood = 1:%d |", n);
for ( i = 0; i < cycles; ++i )
{
++result[function(n)];
}
for ( i = 0; i < sizeof result / sizeof *result; ++i )
{
double percent = result[i] * 100.0 / cycles;
printf(" %d = %6d (%5.2f%%)%c", i, result[i], percent, ",\n"[i]);
fflush(stdout);
}
}
int main(void)
{
int i;
srand(time(0));
for ( i = 1; i < 10; ++i )
{
test(likelihood, i);
}
return 0;
}
/* my output
likelihood = 1:1 | 0 = 499869 (49.99%), 1 = 500131 (50.01%)
likelihood = 1:2 | 0 = 666451 (66.65%), 1 = 333549 (33.35%)
likelihood = 1:3 | 0 = 749825 (74.98%), 1 = 250175 (25.02%)
likelihood = 1:4 | 0 = 800192 (80.02%), 1 = 199808 (19.98%)
likelihood = 1:5 | 0 = 833687 (83.37%), 1 = 166313 (16.63%)
likelihood = 1:6 | 0 = 856950 (85.69%), 1 = 143050 (14.30%)
likelihood = 1:7 | 0 = 875569 (87.56%), 1 = 124431 (12.44%)
likelihood = 1:8 | 0 = 888736 (88.87%), 1 = 111264 (11.13%)
likelihood = 1:9 | 0 = 899771 (89.98%), 1 = 100229 (10.02%)
*/
[/edit]