Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
LagrangeInterpolation
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
2 / 2
5
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 interpolate
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2/**
3 * Jingga
4 *
5 * PHP Version 8.1
6 *
7 * @package   phpOMS\Math\Numerics\Interpolation
8 * @copyright Dennis Eichhorn
9 * @license   OMS License 2.0
10 * @version   1.0.0
11 * @link      https://jingga.app
12 */
13declare(strict_types=1);
14
15namespace phpOMS\Math\Numerics\Interpolation;
16
17/**
18 * Lagrange spline interpolation.
19 *
20 * @package phpOMS\Math\Numerics\Interpolation
21 * @license OMS License 2.0
22 * @link    https://jingga.app
23 * @since   1.0.0
24 */
25final class LagrangeInterpolation implements InterpolationInterface
26{
27    /**
28     * Points for spline interpolation
29     *
30     * @var array<int, array{x:int|float, y:int|float}>
31     * @since 1.0.0
32     */
33    private array $points = [];
34
35    /**
36     * Constructor.
37     *
38     * @param array<int, array{x:int|float, y:int|float}> $points Points to create the interpolation with
39     *
40     * @since 1.0.0
41     */
42    public function __construct(array $points) {
43        $this->points = $points;
44    }
45
46    /**
47     * {@inheritdoc}
48     */
49    public function interpolate(int | float $x) : float
50    {
51        $n      = \count($this->points);
52        $result = 0.0;
53
54        for ($i = 0; $i < $n; ++$i) {
55            $solve = $this->points[$i]['y'];
56            for ($j = 0; $j < $n; ++$j) {
57                if ($j !== $i) {
58                    $solve *= ($x - $this->points[$j]['x']) / ($this->points[$i]['x'] - $this->points[$j]['x']);
59                }
60            }
61
62            $result += $solve;
63        }
64
65        return $result;
66    }
67}