Post Reply 
TVM solve for interest rate, revisited
06-21-2022, 04:40 PM (This post was last modified: 06-29-2022 02:56 PM by Albert Chan.)
Post: #20
RE: TVM solve for interest rate, revisited
(06-18-2022 11:03 PM)Thomas Okken Wrote:  Albert, thank you very much for these algorithms!

I just released Plus42 1.0.8 which incorporates these latest improvements.

TVM improvement nicely remove the need for iterator, using counter to ensure 2 f's before rate search.

Here is an updated Python find_rate(), using sentinel values, instead of counter.
Code:
def find_rate(n, pv, pmt, fv, i=None, verbose=False):
    i0, f0 = i, float('nan')
    for (i,eps,f) in iter_i(n, pv, pmt, fv, i, verbose):
        if i0!=None: i0=None; continue  # skip 1 iteration
        if f != f:    return i, False   # bad f -> bad i
        if f0*f <= 0: return i, True    # locked-in rate
        if abs(f) < abs(f0)): f0=f; continue
        return i-eps, (i == i-eps*0.01)

Above relied on IEEE-754 NaN special propety:
(NaN != x) returns True; all other kinds of NaN comparisons returns False.

We could also remove NaN's ahead of time, using function math.isnan()
Code:
from math import isnan
        
def find_rate(n, pv, pmt, fv, i=None, verbose=False):
    i0, f0 = i, float('nan')
    for (i,eps,f) in iter_i(n, pv, pmt, fv, i, verbose):
        if i0!=None: i0=None; continue  # skip 1 iteration
        if isnan(f):  return i, False   # bad f -> bad i
        if isnan(f0): f0=f; continue    # ensure 2 f's
        if f0*f <= 0: return i, True    # locked-in rate
        if abs(f) < abs(f0): f0=f; continue
        return i-eps, (i == i-eps*0.01)

Udpate: using counter is shorter and simpler Smile
Code:
def find_rate(n, pv, pmt, fv, i=None, verbose=False, c=2):
    for (i,eps,f) in iter_i(n, pv, pmt, fv, i, verbose):
        if c: c-=1; f0=f; continue      # skip iterations
        if f0*f <= 0: return i, True    # locked-in rate
        if abs(f) < abs(f0): f0=f; continue
        return i-eps, (i == i-eps*0.01)
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: TVM solve for interest rate, revisited - Albert Chan - 06-21-2022 04:40 PM



User(s) browsing this thread: 1 Guest(s)