遍历结果,直到 0 javascript

Iterate through result until 0 javascript

本文关键字:javascript 直到 结果 遍历      更新时间:2023-09-26

我写了一个javascript函数,它接受许多变量来产生结果,我需要做的是通过调整传递给函数的百分比值来产生0.00(+/- 0.01(的结果。

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

如果从列表中选择第一项,您将看到表格更新结果,用户可以从那里在Price ($)字段中输入一个值,例如100单击计算,结果面板将显示计算结果。

选择时的 YTM 4.371,产生的结果为 Price ($) = 8.52

我需要实现的是通过遍历 YTM 值并递减或递增 0.001 直到实现此结果来显示0.00 (+/- 0.01)的结果,对于此示例,6.002 的 YTM 使我们足够接近,因为我们对输出中的+/- 0.01变化感到满意。

在小提琴的114线上,有一个if语句,我已经开始了,但现在我被困在了从这里开始的地方。

    if (bondCalculation.calculatedPrice !== 0) {
    }

二叉搜索将起作用。这个想法是从低 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);

要获得此小提琴: http://jsfiddle.net/yow44mzm/

尝试这样的事情,根据需要调整变量/参数:

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;
}