NewtonRaphson::run()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
nc 1
nop 3
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 2
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Nyholm\EffectiveInterest;
6
7
/**
8
 * Newton-Raphsons method to do a numerical analysis to find the effective interest.
9
 *
10
 * {@link https://en.wikipedia.org/wiki/Newton%27s_method}
11
 *
12
 * @author Tobias Nyholm <[email protected]>
13
 */
14
final class NewtonRaphson
15
{
16
    /**
17
     * @var int
18
     */
19
    private $precision;
20
21
    /**
22
     * @param int $precision The number of decimals to care to calculate
23
     */
24 9
    public function __construct(int $precision = 7)
25
    {
26 9
        $this->precision = $precision;
27 9
    }
28
29
    /**
30
     * @param callable $fx
31
     * @param callable $fdx
32
     * @param float    $guess
33
     *
34
     * @return float
35
     */
36 9
    public function run(callable $fx, callable $fdx, float $guess): float
37
    {
38 9
        $errorLimit = pow(10, -1 * $this->precision);
39
        do {
40 9
            $previousValue = $guess;
41 9
            $guess = $previousValue - ($fx($guess) / $fdx($guess));
42 9
        } while (abs($guess - $previousValue) > $errorLimit);
43
44 9
        return $guess;
45
    }
46
}
47