2014-12-09 42 views
-1

我已經寫了一個JavaScript函數,它接受一些變量來產生一個結果,我需要做的是產生一個結果是0.00(+/- 0.01)通過調整百分比值是傳遞給函數。遍歷結果,直到0 javascript

小提琴:http://jsfiddle.net/jerswell/33vyvm6n/

如果從列表中選擇你會看到結果及表更新有一個用戶可以輸入一個值到Price ($)場中的第一項說100點擊計算,結果面板會顯示計算結果。

選中時YTM是4.371其產生的結果的Price ($) = 8.52

我需要實現的是通過經由YTM值和遞減迭代或遞增由0.001直到該結果顯示的0.00 (+/- 0.01)結果在這個例子中,YTM 6.002讓我們足夠接近,因爲我們對輸出中的+/- 0.01差異很滿意。

在線小提琴114有一個if語句,我已經開始,但我現在卡在哪裏從這裏去。

if (bondCalculation.calculatedPrice !== 0) { 

    } 

回答

1

二進制搜索將正常工作。這個想法是從低YTM值0和高值12000開始。然後,取低值和高值的平均值,查看誤差,並相應地調整低或高端。繼續這樣做直到誤差足夠小。

可以更換

if(bondCalculation.calculatedPrice !== 0) { 

    } 

function getPrice(ytm) { 
     return bondCalc(bond_term, bond_coupons, bond_semi_function, ytm, bondFaceValue, xtbPrice).calculatedPrice; 
    } 
    var low = 0, high = 12000, ytm; 
    var count = 0; 
    while (true) { 
     count += 1; 
     if (count == 100) { 
      break; 
     } 
     ytm = (low+high)/2; 
     if (Math.abs(getPrice(ytm)) < 0.0001) { 
      break; 
     } else if (getPrice(ytm) > 0) { 
      low = ytm; 
     } else { 
      high = ytm; 
     } 
    } 
    ytm = Math.round(1000*ytm)/1000; 
    yieldToMaturity.val(ytm); 
    bond_indicative_yield = ytm; 
    bondCalculation = bondCalc(bond_term, bond_coupons, bond_semi_function, bond_indicative_yield, bondFaceValue, xtbPrice); 

獲得此琴:你可以在小提琴看的Javascript http://jsfiddle.net/yow44mzm/

+0

完美!非常感謝這個問題的真正優雅的解決方案。 – 2014-12-09 13:11:42

1

嘗試這樣的事情,調整變量/ PARAMS要求:

if(calculatedPrice !== 0){ 
    var currentPrice = calculatedPrice; 
    var adjustedYTM = ytm + 0.01; 
    calculatedPrice = calculatePrice(ytm, other, params); 

    if(calculatedPrice > currentPrice) 
     adjustedYTM = decrementYTM(ytm); 
    else 
     adjustedYTM = incrementYTM(ytm); 

    ytm = adjustedYTM; 
} 

function incrementYTM(ytm){ 
    while(calculatedPrice > 0){ 
     ytm += 0.01; 
     calculatedPrice = calculatePrice(ytm, other, params); 
    } 
    return ytm; 
} 

function decrementYTM(ytm){ 
    while(calculatedPrice > 0){ 
     ytm -= 0.01; 
     calculatedPrice = calculatePrice(ytm, other, params); 
    } 
    return ytm; 
} 
+0

感謝您的回答,把它調整反映我的代碼,以便我清楚這一點。 – 2014-12-09 13:00:43