0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScript で複利計算シミュレーター

Posted at

複利計算

なんか利子の禁止とかなんとかの記事を見てたら、昔の人(申命記に同胞に対する利子の禁止がある)の計算資源で複利計算をするのは面倒だっただろうなと思いました。
それでプログラミングの練習がてら、複利計算シミュレーターを書いてみたという記事。

  • 着眼
    • イテレータを使ってみたかった
      • Infinity を渡せば無限ループできるらしい
        • JavaScript で Infinity はどんな数字よりも大きな定数として作られている
      • シーケンシャルに値を求める必要がなければ、等比数列の n 番目を求める要領で公式に代入したほうが、誤差がなくてよい
koushiki.js
function compoundFinal(P, r, n, t) {
  return P * Math.pow(1 + r / n, n * t);
}
// 例: 1000円、年利5%(0.05)、年1回、10年
console.log(compoundFinal(1000, 0.05, 1, 10));
// 1628.894626777442
fukuri.js
function* fukuri(ganpon,riritsu){
    let hensai = ganpon
    while (true) {
        hensai = hensai*riritsu
        yield hensai
    }
}

function simulator_fukuri(ganpon,riritsu,max_count){
    if ((!ganpon || !riritsu || !max_count )) {
        console.log("error!");
        console.log(`ganpon:${ganpon}\nriritsu:${riritsu}\nmax_count:${max_count}`);
        return false
    }
    const iter = fukuri(ganpon,1 + riritsu/100);
    const container = [];
    let count = 0;
    for (let i of iter) {
        if (count < max_count){
                console.log(`${count+1}:${i}`);
                const res = {
                    num:count+1,
                    value:i
                };
                container.push(res);
        } else {
            break
        }
        count++
    }
    return container
}

// 元本,利率,回転回数 
// simulator_fukuri(1000,5,12)
// 1:1050
// 2:1102.5
// 3:1157.625
// 4:1215.5062500000001
// 5:1276.2815625000003
// 6:1340.0956406250004
// 7:1407.1004226562504
// 8:1477.455443789063
// 9:1551.3282159785163
// 10:1628.8946267774422
// 11:1710.3393581163143
// 12:1795.8563260221301

  • 感想
    • イテレータのメソッドが意外と少ない
      • 最近 map,filter,forEach などをズラズラ連ねて const だけのプログラムを書くのにハマっているのだが、うまいことできなかった
        • あと for の排除
        • 雑に任意回ブロック内を繰り返せる python の range() 相当の組み込み関数があれば便利じゃないか
         // もちろん下のようにできるけど、来週には覚えている自信がない
         // パッと見でこれの意味がよくわからない気がする
         [...Array(n).keys()]
           .forEach((iteration) => {f()})
         
         // for でいいじゃないかという説もある
         Array(n)
           .fill(0)
           .forEach((iteration) => {f()})

Link

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?