Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. package playground
  2.  
  3. class Balance(months : Int, borrowed : Double, rate : Double){
  4.  
  5. def balance_(months : Int, borrowed : Double, rate : Double, payment : Double) : Double =
  6. {
  7. if(months == 0) borrowed
  8. else rate * balance_(months - 1, borrowed, rate, payment) - payment
  9. }
  10.  
  11. val balance = balance_(this.months, this.borrowed, this.rate, _ : Double)
  12.  
  13. def bisection(f : Double => Double, reps : Int, guess1 : Double, guess2 : Double) : Double =
  14. {
  15. def sign(x : Double) : Int =
  16. {
  17. x match{
  18. case y if y < 0 => -1
  19. case y if y > 0 => 1
  20. case _ => 0
  21. }
  22. }
  23.  
  24. val guess3 = (guess1 + guess2)/2
  25.  
  26. if(reps == 0 || f(guess3) == 0) guess3
  27. else{
  28. val s = sign(f(guess1)/f(guess3))
  29. s match{
  30. case 0 => guess1
  31. case (-1) => bisection(f, reps - 1, guess1, guess3)
  32. case _ => bisection(f, reps - 1, guess2, guess3)
  33. }
  34.  
  35. }
  36. }
  37. } // End of the Balance class.
  38.  
  39. object Balance extends App{
  40.  
  41. import scala.io.StdIn._
  42.  
  43. println("")
  44.  
  45. print("How much money are you going to borrow? ")
  46. val borrowed = readDouble()
  47.  
  48. print("How many years will it take to repay the loan? ")
  49. val years = readInt()
  50.  
  51. print("What is the annual interest rate expressed as a percentage? ")
  52. val percent = readDouble()
  53.  
  54. val months = 12*years
  55. val rate = 1 + percent/1200
  56.  
  57. print("How many times do you want to implement the bisection algorithm? ")
  58. val reps = readInt()
  59.  
  60. val mortgage = new Balance(months, borrowed, rate)
  61.  
  62. val payment = mortgage.bisection(mortgage.balance, reps, borrowed, 0)
  63.  
  64. val totalInterest = months * payment - borrowed
  65.  
  66. val balanceEachMonth = for (month <- (0 to months).toList)
  67. yield (month, mortgage.balance_(month, borrowed, rate, payment))
  68.  
  69. printf("\nYour monthly mortgage payment is $%,.2f", payment)
  70.  
  71. printf("\nThe total interest on the loan after %d years is $%,.2f", years, totalInterest)
  72.  
  73. println("\n")
  74.  
  75. balanceEachMonth.foreach(t => { print("Month: \t" + t._1); print(", \t")
  76. printf("Amount Owed: \t$%,.2f", t._2); println(""); Thread.sleep(350L) })
  77.  
  78. println("\n")
  79.  
  80. } // End of the Balance companion object.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement