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で実装する複利計算 — 高速累乗法 O(log n)

0
Posted at

複利計算の公式は A = P × (1 + r/n)^(n×t) です。一見シンプルですが、大きな指数を効率的に計算するには工夫が必要です。

問題:指数が大きい

日次複利(n=365)で t=50年の場合、指数は 365×50 = 18,250 になります。つまり (1.00019)^18250 を計算する必要があります。

ナイーブな実装:

function compound(P, r, n, t) {
return P * Math.pow(1 + r / n, n * t);
}

Math.pow() は内部的に対数を使うので O(1) ですが、金融計算でより細かい制御が必要な場合もあります。

高速累乗法(バイナリ法)

O(log n) で動作する exponentiation by squaring:

function fastPow(base, exp) {
let result = 1;
while (exp > 0) {
if (exp & 1) result *= base; // 最下位ビットが1なら掛ける
base *= base; // 基数を2乗
exp >>= 1; // 指数を右シフト
}
return result;
}

指数 18,250 に対して、ナイーブなループ(18,250回)と比較して、高速累乗法はわずか約15回の乗算で済みます。

複利計算への適用:

function compoundFast(P, r, n, t) {
const base = 1 + r / n;
const exp = n * t;
return P * fastPow(base, exp);
}

実用的な拡張:積立対応

現実には積立頻度(例:隔週)と複利頻度(例:毎日)が異なります。両方を独立して扱う実装が必要です。

完全な実装とデモはこちら:https://finikit.com/tools/compound-calculator.html

0
0
0

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?