phit

Densities, quantiles, and random draws

On this page

Evaluate a normal distribution with mean 100 and standard deviation 15, compare Student’s t critical values with the normal’s, and draw seeded random numbers.

The example prints tables with phibble (composer require phpstats/phibble) and runs with the phit extension or the plain-PHP polyfill (Extension or polyfill).

Code

use Phibble\DataFrame;use function Phit\{dist_normal_cdf, dist_normal_pdf};use function Phit\{dist_normal_quantile, dist_normal_rng};use function Phit\dist_normal_sf;use function Phit\{dist_t_quantile, dist_t_sf};// Normal with mean 100 and SD 15.echo DataFrame::fromColumns([    'quantity' => ['density at 115', 'P(X <= 130)', 'quantile 0.95'],    'value' => [        dist_normal_pdf(115, 100, 15),        dist_normal_cdf(130, 100, 15),        dist_normal_quantile(.95, 100, 15),    ],]), "\n\n";// Two-sided 95% critical values, and P(|T| > 1.96).$df = [3, 10, 30];echo DataFrame::fromColumns([    'distribution' => ['t, df 3', 't, df 10', 't, df 30', 'normal'],    'critical' => [        ...array_map(fn ($v) => dist_t_quantile(0.975, $v), $df),        dist_normal_quantile(0.975),    ],    'tail' => [        ...array_map(fn ($v) => 2 * dist_t_sf(1.96, $v), $df),        2 * dist_normal_sf(1.96),    ],]), "\n\n";echo implode(', ', dist_normal_rng(5, 42, 100, 15)), "\n";$many = dist_normal_rng(100000, 7, 100, 15);echo 'mean of 100000 draws ', array_sum($many) / count($many), "\n";

Output

# A tibble: 3 × 2
  quantity          value
  <chr>             <dbl>
1 density at 115   0.0161
2 P(X <= 130)      0.977 
3 quantile 0.95  125.    

# A tibble: 4 × 3
  distribution critical   tail
  <chr>           <dbl>  <dbl>
1 t, df 3          3.18 0.145 
2 t, df 10         2.23 0.0784
3 t, df 30         2.04 0.0593
4 normal           1.96 0.0500

100.52835466511, 96.594495946498, 80.588363237338, 85.533635781581, 85.276248423651
mean of 100000 draws 99.995690773619

Notes

  • _pdf, _cdf, _quantile, and _sf correspond to R’s dnorm(), pnorm(), qnorm(), and pnorm(lower.tail = FALSE).
  • _sf keeps precision far into the upper tail, where 1 - cdf loses it.
  • Student’s t has heavier tails than the normal. Its values approach the normal’s as the degrees of freedom grow.
  • Each dist_normal_rng($n, $seed, $mean, $sd) call starts its own stream from the seed, so the same seed and parameters give the same draws.

See also: Probability distributions for every family and its parameters · Seeded sampling for the generator