コード例 #1
0
 def test_simple(self):
     # has only one root 1
     f = lambda x: x**2 - 2 * x + 1
     root, iters, obs_eps = find_root_newton(
         f, 0.5, f_der=lambda x: approx_derivative_symmetric(f, x, 1E-8))
     assert root == pytest.approx(0.9999923713783172)
     assert iters == 16
     assert obs_eps == pytest.approx(5.819589254940638e-11)
コード例 #2
0
 def test_exact_derivative_gives_comparable_results(self):
     """note it isn't always better - by careful choosing of h in numerical diff test_simple
     actually gives closer answer in same number of iterations"""
     # has only one root 1
     f = lambda x: x**2 - 2 * x + 1
     f_der = lambda x: 2 * x - 2
     root, iters, obs_eps = find_root_newton(f, 0.5, f_der=f_der)
     assert root == pytest.approx(0.9999923706054688)
     assert iters == 16
     assert obs_eps == pytest.approx(5.820766091346741e-11)
コード例 #3
0
ファイル: instruments.py プロジェクト: ipalopezhentsev/python
    def irr(self) -> float:
        """
        Returns internal rate of return (in terms of 1)
        For irr to be present, there must be both positive and negative flows.

        The internal rate of return on an investment or project is the "annualized effective
        compounded return rate" or rate of return that sets the net present value of all
        cash flows (both positive and negative) from the investment equal to zero.

        It is the discount rate at which the net present value of the future cash flows
        is equal to the initial investment, and it is also the discount rate at which the
        total present value of costs (negative cash flows) equals the total present value
        of the benefits (positive cash flows).
        https://en.wikipedia.org/wiki/Internal_rate_of_return#Exact_dates_of_cash_flows
        """
        r0 = 0.0
        for flow in self.flows[1:]:
            r0 += flow.flow
        r0 = (-1.0 / self.flows[0].flow) * r0 - 1.0
        irr, _, _ = find_root_newton(f=lambda r: self.npv(r),
                                     init_guess=r0,
                                     f_der=lambda r: self.npv_der(r))
        return irr
コード例 #4
0
 def test_cannot_converge(self):
     # doesn't have roots
     f = lambda x: x**2 - 2 * x + 2
     with pytest.raises(ValueError):
         find_root_newton(f, 2.0)
コード例 #5
0
 def test_already_converged(self):
     f = lambda x: x**2 - 2 * x + 1
     root, iters, obs_eps = find_root_newton(f, 1.0)
     assert root == 1.0
     assert iters == 0
     assert obs_eps == 0.0