Completed
Push — master ( a3da9c...ba4a7f )
by Tobias
23:20
created

NewtonRaphson::doCalculate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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