I am getting having errors with the math in my loan repayment calculator. I am trying to create a class where I can create a loan, iterate it by month or year, and also apply payments to the loan. I am not entirely sure where my issue lies in this code.
I've tried altering the payment method and am stuck with the root problem with the math. I think there is an underlying issue with the way that I have interest accruing and the principle balance
class loan():
p_i = 0 #initial principle
p_new = 0 #total balance
rate = 0 #interest rate (in %)
acc = 0 #total accrued interest
def __init__(self,p,rate):
self.p_i = p
self.p_new = p
self.rate = rate
def month(self):
if self.p_i == self.p_new:
self.acc += self.p_i * (1 + (self.rate/100)/12)
self.p_new = self.p_i + self.acc
else:
self.acc += self.p_i * (1 + (self.rate/100)/12)
self.p_new = self.p_i + self.acc
def year(self):
if self.p_i == self.p_new:
self.acc += self.p_i * (1 + (self.rate/100)) - self.p_i
self.p_new = self.p_i + self.acc
else:
temp = 0
temp = self.p_i * (1 + (self.rate/100)) - self.p_i
self.p_new += temp
self.acc += temp
def payment(self,amount):
temp = 0
if amount < self.acc:
self.acc -= amount
else:
self.p_i -= amount - self.acc
self.acc = 0
self.p_new -= amount
I would expect the output for say, a 10000 dollar loan with a 5% interest rate to be 10500 and then 11025 and the accrued interest to be 1025, instead I am getting 11000 and 1000 respectively.
I would recommend as a start that you take this out of a class and just do this procedurally until you get the math worked out. It seems you are battling the
classsyntax a bit.So just try setting variables and some functions and then looping through some options.
Start with something like this:
Realize this is kinda ugly with global variables and all, but if you are having trouble getting the math to work, start here and then build to a class later when you have the kinks worked out.
Output: