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

NewtonRaphson   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 3
lcom 1
cbo 0
dl 0
loc 34
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A run() 0 11 2
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