-
Notifications
You must be signed in to change notification settings - Fork 241
/
Copy pathbinomial.c
86 lines (69 loc) · 2 KB
/
binomial.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <stdio.h>
#include <math.h>
int factorial(int x)
{
return (x == 0) ? 1 : x * factorial(x - 1);
}
double calculateProbability(int n, float p, int r, int ch)
{
double q = 1.0 - p;
double result = 0;
double term;
switch (ch)
{
case 1: // At least r success
for (int i = r; i <= n; i++)
{
term = (factorial(n) / (factorial(n - i) * factorial(i))) * pow(p, i) * pow(q, (n - i));
result += term;
}
break;
case 2: // At most r success
for (int i = 0; i <= r; i++)
{
term = (factorial(n) / (factorial(n - i) * factorial(i))) * pow(p, i) * pow(q, (n - i));
result += term;
}
break;
case 3: // Exactly r success
term = (factorial(n) / (factorial(n - r) * factorial(r))) * pow(p, r) * pow(q, (n - r));
result = term;
break;
case 4: // Not r success
term = (factorial(n) / (factorial(n - r) * factorial(r))) * pow(p, r) * pow(q, (n - r));
result = 1.0 - term;
break;
default:
printf("Wrong choice");
break;
}
return result;
}
int main()
{
int n, r, choice;
float p;
printf("Enter number of occurrence of events(n): ");
scanf(" %d", &n);
printf("Enter the probability of success(p): ");
scanf("%f", &p);
if (p < 0 || p > 1)
{
printf("Probability lies between 0 and 1");
return 1;
}
printf("Enter the number of times success is occurring(r)[r cannot be decimal]: ");
scanf("%d", &r);
if (r < 0 || r > n)
{
printf("Value of r lies between 0 and n");
return 1;
}
printf("Enter your operation from the following: \n");
printf("1. At least r success \n2. At most r success \n3. r success \n4. not r \n");
scanf("%d", &choice);
double prob = calculateProbability(n, p, r, choice);
printf("\n----------------ANSWER-----------------\n");
printf("The required probability is %f", prob);
return 0;
}