factorial(1:10)
[1] 1 2 6 24 120 720 5040 40320 362880
[10] 3628800
For this lab, we will implement a class representing a binomial distribution:
\[ \Pr{\left(Y=k; n, p\right)} = {n \choose k}p^k(1-p)^{n-k} \]
Implement the following class representing a binomial distribution:
class Binom {
private:
int n;
double p;
public:
// Binom(int n_, double p_) : n(n_), p(p_) {};
(int n_, double p_) {
Binom= n_;
n = p_;
p };
int factorial(int k) const;
double choose(int a, int b) const;
double dbinom(int k) const;
void print(int k) const;
};
Remember that to implement the function, you have to use the following pattern:
inline [return type] [class name]::[function name]([arguments]) {
// Your code here
}
Write a program that implements the factorial
function. It should match the following results in R
factorial(1:10)
[1] 1 2 6 24 120 720 5040 40320 362880
[10] 3628800
You can use the following code to test your function:
(10, 0.5);
Binom bfor (int i = 0; i < 10; i++) {
std::cout << b.factorial(i) << std::endl;
}
Write a program that implements the choose
function. It should match the following results in R
choose(10, 1:10)
[1] 10 45 120 210 252 210 120 45 10 1
You can use the following code to test your function:
(10, 0.5);
Binom bfor (int i = 0; i < 10; i++) {
std::cout << b.choose(10, i) << std::endl;
}
Write a program that implements the dbinom
function. It should match the following results in R
dbinom(0:10, 10, 0.5)
[1] 0.0009765625 0.0097656250 0.0439453125 0.1171875000 0.2050781250
[6] 0.2460937500 0.2050781250 0.1171875000 0.0439453125 0.0097656250
[11] 0.0009765625
You can use the following code to test your function:
(10, 0.5);
Binom bfor (int i = 0; i < 10; i++) {
std::cout << b.dbinom(i) << std::endl;
}
Write a program that implements the print
function. It should match the following results in R
sprintf(
"P(Y=%-2d; n=%d, p=%.2f) = %.4f",
0:10, 10, 0.5, dbinom(0:10, 10, 0.5)
|>
) cat(sep = "\n")
P(Y=0 ; n=10, p=0.50) = 0.0010
P(Y=1 ; n=10, p=0.50) = 0.0098
P(Y=2 ; n=10, p=0.50) = 0.0439
P(Y=3 ; n=10, p=0.50) = 0.1172
P(Y=4 ; n=10, p=0.50) = 0.2051
P(Y=5 ; n=10, p=0.50) = 0.2461
P(Y=6 ; n=10, p=0.50) = 0.2051
P(Y=7 ; n=10, p=0.50) = 0.1172
P(Y=8 ; n=10, p=0.50) = 0.0439
P(Y=9 ; n=10, p=0.50) = 0.0098
P(Y=10; n=10, p=0.50) = 0.0010