Created
November 10, 2014 21:48
-
-
Save vargonaut/c71a54da892554c2d42a to your computer and use it in GitHub Desktop.
Calculate payments for getting paid off in a certain time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| require 'date' | |
| class Repayment | |
| MONTHLY_INTEREST = (<INTEREST (5.00)> / 12 / 100) | |
| def initialize(payment, principal) | |
| @payment, @principal = payment, principal | |
| end | |
| def self.summarize(principal, payments) | |
| old_repayment_count = 0 | |
| payments.each do |payment| | |
| repayment = Repayment.new payment, principal | |
| maybe_summarize repayment, old_repayment_count | |
| old_repayment_count = repayment.number_of_payments | |
| end | |
| end | |
| def summarize | |
| puts | |
| puts '-' * 40 | |
| puts 'Payment: $ %.2f' % payment | |
| puts 'Payments: %.2d' % number_of_payments | |
| puts 'Paid off: %s' % (Date.today >> number_of_payments).strftime("%b '%y") | |
| end | |
| def number_of_payments | |
| @number_of_payments ||= calculate_number_of_payments | |
| end | |
| private | |
| attr_reader :payment, :principal | |
| def self.maybe_summarize repayment, num_payments | |
| repayment.summarize unless repayment.number_of_payments == num_payments | |
| end | |
| def calculate_number_of_payments | |
| numerator = -1 * Math.log10(1 - MONTHLY_INTEREST * principal / payment) | |
| denominator = Math.log10(1 + MONTHLY_INTEREST) | |
| (numerator / denominator).ceil | |
| end | |
| end | |
| payments = (<MIN PAYMENT..<MAX PAYMENT>).step(0.01) | |
| principal = <LOAN AMOUNT> | |
| Repayment.summarize(principal, payments) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment