# Hi, I'm Ataias Reis

Programmer, made in Brazil, Alma mater University of Brasilia

# 30 days of code in Go: Day 19 - Binomial Distribution II

Hi there! Today's problem is very similar to the last day, again using a binomial distribution.

### Question

Given that 12% of the pistons of a manufacture are rejected because of incorrect sizing, what is the probability of batch of 10 pistons contain

1. No more than two rejects?
2. At least two rejects?

Again, very similar. Now the probability of success for the Bernoulli trial is of the chance of the piston being reject, the same as being incorrectly sized. For the case of no more than two rejects, the probability is given by $$P_{x \le 2} = \sum_{i=0}^2 b(i, 10, 0.12),$$ while for the case of at least two rejects it is $$P_{x \ge 2} = \sum_{i=2}^{10} b(i, 10, 0.12).$$

### Code

My solution is pretty similar to my last one and is presented below. Just the main function was changed.

package main

import (
"fmt"
"math"
)

func factorial(n int) int {
if n <= 1 {
return 1
} else {
return n * factorial(n-1)
}
}

func b(x, n int, p float64) float64 {
comb_n_x := float64(factorial(n) /
factorial(x) /
factorial(n-x))
p_x := math.Pow(p, float64(x))
q_n_x := math.Pow(1.0-p, float64(n-x))
return comb_n_x * p_x * q_n_x

}

func main() {

percentage := 0.0
fmt.Scanf("%f", &percentage)

// probability of a defect
p := percentage / 100.0

// total number of trials
n := 0
fmt.Scanf("%d", &n)

// probability of having
// no more than 2 rejects
probability1 := 0.0
for i := 0; i <= 2; i++ {
probability1 += b(i, n, p)
}

fmt.Printf("%.3f\n", probability1)

// probability of having
// at least 2 rejects
probability2 := 0.0
for i := 2; i <= n; i++ {
probability2 += b(i, n, p)
}

fmt.Printf("%.3f\n", probability2)
}


Below I ran it and I commented the output.

$go build day_19.go$ ./day_19
12 10
0.891 # P of <= 2 defects
0.342 # P of >= 2 defects