Skip to content

Instantly share code, notes, and snippets.

@ryoppippi
Last active February 7, 2016 14:21
Show Gist options
  • Select an option

  • Save ryoppippi/6af7725c653c4425715a to your computer and use it in GitHub Desktop.

Select an option

Save ryoppippi/6af7725c653c4425715a to your computer and use it in GitHub Desktop.
Calculate "net present value" for economics assignment
//: Playground - noun: a place where people can play
//:累乗をするための関数を定義する
func jyou(n : Double, x:Int) -> Double {
var ans = 1.0
for _ in 1...x{
ans *= n
}
return ans
}
//:割引現在価値を求める関数を以下に定義する(コンソル債の時はendYear = nilとする)。StartとEndの間は利子のみが払われている
func calc(startYear : Int , endYear : Int?, price : Double, interest : Double, intRate : Double) -> Double{
if endYear == nil{
return(interest/intRate)
}
else {
var X = 0
var answer = 0.00
for x in 1..<(endYear!-startYear+2){
answer += interest / jyou(intRate+1, x: x)
X = x
}
answer += price / jyou(intRate+1, x: X+1) //:返済される年
return(answer)
}
}
//:金利と額面を定義しておく
let interestPrice = 400.00
let backPrice = 10400.00
//:以下が解答
//:市場金利2%の場合
print(calc(2017, endYear: 2020, price: backPrice, interest: interestPrice, intRate: 0.02))
print(calc(2017, endYear: 2025, price: backPrice, interest: interestPrice, intRate: 0.02))
print(calc(2017, endYear: nil, price: backPrice, interest: interestPrice, intRate: 0.02))
//:市場金利4%の場合
print(calc(2017, endYear: 2020, price: backPrice, interest: interestPrice, intRate: 0.04))
print(calc(2017, endYear: 2025, price: backPrice, interest: interestPrice, intRate: 0.04))
print(calc(2017, endYear: nil, price: backPrice, interest: interestPrice, intRate: 0.04))
//:市場金利6%の場合
print(calc(2017, endYear: 2020, price: backPrice, interest: interestPrice, intRate: 0.06))
print(calc(2017, endYear: 2025, price: backPrice, interest: interestPrice, intRate: 0.06))
print(calc(2017, endYear: nil, price: backPrice, interest: interestPrice, intRate: 0.06))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment