2013-01-04 105 views
7

我試圖在JavaScript中實現Microsoft Excel的GROWTH函數。此函數通過使用現有數據來計算預測的指數增長。棘手的是它必須與多組known_x's值配合使用。我找不到任何參考方程式。有什麼建議麼?如何在JavaScript中實現GROWTH函數

在此先感謝您的幫助。

+4

您可能會問[math.stackexchange.com](http://math.stackexchange.com) –

+0

感謝您的建議。會做! –

回答

1

下面是基於my answer at math.SE重新實現從維基百科頁面的simple linear regression公式:

function growth (known_y, known_x, new_x, use_const) { 
    // default values for optional parameters: 
    if (typeof(known_x) == 'undefined') { 
     known_x = []; 
     for (var i = 1; i <= known_y.length; i++) known_x.push(i); 
    } 
    if (typeof(new_x) == 'undefined') { 
     new_x = []; 
     for (var i = 1; i <= known_y.length; i++) new_x.push(i); 
    } 
    if (typeof(use_const) == 'undefined') use_const = true; 

    // calculate sums over the data: 
    var n = known_y.length; 
    var avg_x = 0; var avg_y = 0; var avg_xy = 0; var avg_xx = 0; 
    for (var i = 0; i < n; i++) { 
     var x = known_x[i]; var y = Math.log(known_y[i]); 
     avg_x += x; avg_y += y; avg_xy += x*y; avg_xx += x*x; 
    } 
    avg_x /= n; avg_y /= n; avg_xy /= n; avg_xx /= n; 

    // compute linear regression coefficients: 
    if (use_const) { 
     var beta = (avg_xy - avg_x*avg_y)/(avg_xx - avg_x*avg_x); 
     var alpha = avg_y - beta*avg_x; 
    } else { 
     var beta = avg_xy/avg_xx; 
     var alpha = 0; 
    } 
    // console.log("alpha = " + alpha + ", beta = " + beta); 

    // compute and return result array: 
    var new_y = []; 
    for (var i = 0; i < new_x.length; i++) { 
     new_y.push(Math.exp(alpha + beta * new_x[i])); 
    } 
    return new_y; 
} 

Here's a demo on ideone.com.您可以比較在Excel GROWTH documentation page演示表的輸出。

請注意,算法中求和迴路的數值穩定性可以通過使用諸如calculating the variance的維基百科頁面上描述的技術來改進,如Kahan summation。然而,對於這樣的簡單例子,天真的求和循環相當不錯。

+0

你搖滾!萬分感謝。我使用了你的代碼,並在http://stoic.com/formula和http://stoic.com/formula/lib/formula.js的代碼庫中給了你功勞 –