Skip to content

Commit

Permalink
Merge pull request #78 from Hi-Folks/feat/normaldist-fromsamples
Browse files Browse the repository at this point in the history
Implementing fromSample method for NormalDist
  • Loading branch information
roberto-butti authored Dec 13, 2024
2 parents 16c8adf + a5d15c8 commit 3448a85
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# Changelog

## 1.1.1 - 2024-12-13
- Implementing fromSample method for NormalDist

## 1.1.0 - 2024-12-13
- Upgrading RectorPHP v 2
- Upgrading PHPStan v 2
Expand Down
33 changes: 33 additions & 0 deletions src/NormalDist.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,45 @@ public function getMean(): float
{
return $this->mu;
}
public function getMeanRounded(int $precision = 3): float
{
return round($this->getMean(), $precision);
}

// Getter for standard deviation (read-only)
public function getSigma(): float
{
return $this->sigma;
}
public function getSigmaRounded(int $precision = 3): float
{
return round($this->getSigma(), $precision);
}

/**
* Creates a NormalDist instance from a set of data samples.
*
* This static method calculates the mean (μ) and standard deviation (σ)
* from the provided array of numeric samples and initializes a new
* NormalDist object with these values.
*
* @param float[] $samples An array of numeric samples to calculate the distribution.
* The array must contain at least one element.
*
* @return NormalDist Returns a new NormalDist object with the calculated mean and standard deviation.
*
* @throws InvalidDataInputException If the samples array is empty or contains non-numeric values.
*
*/
public static function fromSamples(array $samples): self
{
if ($samples === []) {
throw new InvalidDataInputException("Samples array must not be empty.");
}
$mean = Stat::mean($samples);
$std_dev = Stat::stdev($samples);
return new self((float) $mean, $std_dev);
}

// A utility function to calculate the probability density function (PDF)
public function pdf(float $x): float
Expand Down
14 changes: 14 additions & 0 deletions tests/NormalDistTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,17 @@
$nd->pdfRounded(12, 2),
)->toEqual(0.12);
});

it(' load normal dist from samples', function (): void {
// NormalDist.from_samples([2.5, 3.1, 2.1, 2.4, 2.7, 3.5])
// NormalDist(mu=2.716666666666667, sigma=0.5076087732365021)
$samples = [2.5, 3.1, 2.1, 2.4, 2.7, 3.5];
$normalDist = NormalDist::fromSamples($samples);

expect(
$normalDist->getMeanRounded(5),
)->toEqual(2.71667);
expect(
$normalDist->getSigmaRounded(5),
)->toEqual(0.50761);
});

0 comments on commit 3448a85

Please sign in to comment.