Guest User

Untitled

a guest
May 21st, 2018
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. # given principal and interest rate
  2. # + periods = minimum payment amount and total cost
  3. # + extra payment = periods, total cost, and savings over minimum
  4.  
  5. import math
  6.  
  7. def calculate(principal,rate_yearly,periods,extra=0):
  8.  
  9. # variables
  10. rate_monthly = rate_yearly / 12 / 100
  11.  
  12. # calculate minimum payment
  13. if rate_monthly > 0:
  14. payment = rate_monthly * principal / (1 - (1 + rate_monthly)**(-periods))
  15. else:
  16. payment = principal / periods
  17. payment = round(payment,2)
  18.  
  19. # calculate costs at minimum payment
  20. total = payment * periods
  21. interest = total - principal
  22. interest = round(interest,2)
  23.  
  24. # calculate payment with extra
  25. if extra:
  26. payment_extra = payment + extra
  27. payment_extra = round(payment_extra,2)
  28.  
  29. # calculate period with extra
  30. if extra:
  31. periods_extra = -(math.log(-(rate_monthly * principal / payment_extra) + 1) / math.log(1 + rate_monthly)) # yes, this uses log, so thank your high school math teacher
  32. periods_extra = round(periods_extra,1)
  33. months_extra = periods - periods_extra
  34. months_extra = round(months_extra,1)
  35.  
  36. # calculate costs with extra
  37. if extra:
  38. total_extra = payment_extra * periods_extra
  39. interest_extra = total_extra - principal
  40. interest_extra = round(interest_extra,2)
  41. savings_extra = interest - interest_extra
  42. savings_extra = round(savings_extra,2)
  43.  
  44. # output
  45. print("\n"*3)
  46. print(f"For a loan of ${principal} at a {rate_yearly}% interest rate, your minimum payment will be ${payment} per month for {periods} months, and you'll pay a total ${interest} in interest.")
  47. if extra:
  48. print(f"\nIf you pay ${extra} extra per month, your payments will be ${payment_extra} per month for {periods_extra} months, and you'll pay a total ${interest_extra} in interest. That's ${savings_extra} less and {months_extra} months faster than if you only pay the minimum!")
  49. print("\n"*3)
  50.  
  51. # run the calculator
  52. calculate(
  53. principal = 100000 - 10000, # the amount of the loan, you can put the total cost minus down payment as well as shown here
  54. rate_yearly = 5, # yearly interest rate out as a percent
  55. periods = 30 * 12, # number of months for repayment, or as shown here, years for repayment times twelve
  56. extra = 1000 # any extra you can pay each month above and beyond the minimum payment
  57. )
Add Comment
Please, Sign In to add comment