# How do I count the defects in a batch?

A batch of parts holds a number of defective ones, each defective with the same chance. The count is Binomial, and one part is the Bernoulli case. The script charges one minute of rework per defect.

```python
from nagasim import build as nb

# A batch of 20 parts, each defective with probability 0.1 (Binomial). Every defect costs one minute
# of rework, so the rework delay is the defect count. A single part is the Bernoulli case: p of
# one minute, otherwise none.
m = nb.Model(time_limit=4000, warmup=0)
m.add_resource(name="Rework")
batches = m.create(distribution=nb.Exponential(rate=1 / 4))
batches >> m.process(resource_name="Rework", distribution=nb.Binomial(n=20, p=0.1)) >> m.dispose()

results = m.run(replications=10, seed=1)
print(f"rework bench busy {results.kpi('resource/Rework/Usage % (snapshot)'):.0f}% (2 defects in 4 minutes is 50%)")

single = nb.Model(time_limit=4000, warmup=0)
single.add_resource(name="Rework")
single.create(distribution=nb.Exponential(rate=1 / 4)) >> single.process(
    resource_name="Rework", distribution=nb.Bernoulli(p=0.5)) >> single.dispose()
busy = single.run(replications=10, seed=1).kpi("resource/Rework/Usage % (snapshot)")
print(f"single part, Bernoulli(0.5): busy {busy:.0f}% (0.5 minute in 4 is 12.5%)")

```

Save it as `recipe-binomial-defects.py` and run it with `python`. The script seeds itself, so the numbers below are the same on your machine.

```text
rework bench busy 50% (2 defects in 4 minutes is 50%)
single part, Bernoulli(0.5): busy 13% (0.5 minute in 4 is 12.5%)

```

## How it works

1. `Binomial(n, p)` is the defect count in `n` parts when each is bad with probability `p`; the mean is `n * p`.
2. `Bernoulli(p)` is a single yes-or-no part, returning 1 with probability `p` and 0 otherwise.
3. A batch of 20 with `p = 0.1` has 2 defects on average, which is 2 minutes of rework every 4 minutes.

## Elements used

- Distributions: [Binomial](../../reference/distributions/binomial.md), [Bernoulli](../../reference/distributions/bernoulli.md), [Exponential](../../reference/distributions/exponential.md).
- Blocks: [CREATE](../../reference/blocks/create.md), [PROCESS](../../reference/blocks/process.md), [DISPOSE](../../reference/blocks/dispose.md).
- Python: [`Model`](../../reference/api/Model.md).

Back to all [recipes](index.md).
