Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package playground
- class Balance(months : Int, borrowed : Double, rate : Double){
- def balance_(months : Int, borrowed : Double, rate : Double, payment : Double) : Double =
- {
- if(months == 0) borrowed
- else rate * balance_(months - 1, borrowed, rate, payment) - payment
- }
- val balance = balance_(this.months, this.borrowed, this.rate, _ : Double)
- def bisection(f : Double => Double, reps : Int, guess1 : Double, guess2 : Double) : Double =
- {
- def sign(x : Double) : Int =
- {
- x match{
- case y if y < 0 => -1
- case y if y > 0 => 1
- case _ => 0
- }
- }
- val guess3 = (guess1 + guess2)/2
- if(reps == 0 || f(guess3) == 0) guess3
- else{
- val s = sign(f(guess1)/f(guess3))
- s match{
- case 0 => guess1
- case (-1) => bisection(f, reps - 1, guess1, guess3)
- case _ => bisection(f, reps - 1, guess2, guess3)
- }
- }
- }
- } // End of the Balance class.
- object Balance extends App{
- import scala.io.StdIn._
- println("")
- print("How much money are you going to borrow? ")
- val borrowed = readDouble()
- print("How many years will it take to repay the loan? ")
- val years = readInt()
- print("What is the annual interest rate expressed as a percentage? ")
- val percent = readDouble()
- val months = 12*years
- val rate = 1 + percent/1200
- print("How many times do you want to implement the bisection algorithm? ")
- val reps = readInt()
- val mortgage = new Balance(months, borrowed, rate)
- val payment = mortgage.bisection(mortgage.balance, reps, borrowed, 0)
- val totalInterest = months * payment - borrowed
- val balanceEachMonth = for (month <- (0 to months).toList)
- yield (month, mortgage.balance_(month, borrowed, rate, payment))
- printf("\nYour monthly mortgage payment is $%,.2f", payment)
- printf("\nThe total interest on the loan after %d years is $%,.2f", years, totalInterest)
- println("\n")
- balanceEachMonth.foreach(t => { print("Month: \t" + t._1); print(", \t")
- printf("Amount Owed: \t$%,.2f", t._2); println(""); Thread.sleep(350L) })
- println("\n")
- } // End of the Balance companion object.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement