2014-02-17 80 views
0

我有“scaledValue”,我想找到“价值”,我可以反转此功能吗?

但似乎不可能? (接受相似的值)

var priceBound = [0, 10000000]; 
var priceCurves = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1.2, 1.4, 1.6, 1.8, 5, 35, 70, 100]; 

function calcScaledPrice(Value) { 
    var currentValue = Value; 
    var currentFixed = Value - priceBound[0]; 

    var fixedBound = priceBound[1] - priceBound[0]; 

    var currentPercent = Math.round((currentFixed/fixedBound) * 20); 
    var currentScale = priceCurves[currentPercent]; 
    var scaledValue = Math.round(currentValue * (currentScale/100)); 

    return scaledValue; 
} 
+0

你想把它作为一个等式来解决吗?或将console.log(值)足够? –

+0

如果它是一种双射,它是可逆的:如果它是一对一的并且在上面。 –

+0

如果'scaledValue = currentValue * currentScale/100'则解决* currentValue *:'currentValue = scaledValue * 100/currentScale'。 – RobG

回答

0

没有单个输入值可以生成特定的输出值,因此无法提供确定的答案。但是,可能会生成一个值,这会导致特定的缩放值,只是它不会是唯一的。例如

calcScaledPrice(150)); // 2 
calcScaledPrice(200)); // 2 

以下生成一系列候选值,然后返回第一个创建合适的缩放值。不是特别优雅,但它可以完成这项工作(只需轻微测试,以便谨慎使用)。还有其他的迭代方法,例如使用一种二进制搜索算法来找到合适的值。

function calcValue(scaledValue) { 
    var fixedBound = priceBound[1] - priceBound[0]; 
    var possibleCurrentValues = []; 
    var currentFixed, currentScale, value; 

    // Generate a matrix of possible values 
    for (var i=0, iLen=priceCurves.length; i<iLen; i++) { 
     possibleCurrentValues.push(Math.round(scaledValue * 100/priceCurves[i])); 
    } 

    // Return the first possibleCurrentValue that generates 
    // a suitable scaled value 
    for (var j=0, jLen=possibleCurrentValues.length; j<jLen; j++) { 
     value = possibleCurrentValues[j] 
/* 
     // Do the calculation of calcScaledPrice 
     currentFixed = value - priceBound[0];  
     currentPercent = Math.round((currentFixed/fixedBound) * 20); 
     currentScale = priceCurves[currentPercent]; 

     if (Math.round(value * currentScale/100) == scaledValue) { 
      return value; 
     } 
*/ 
     // Simpler, depends on calcScaledPrice function 
     if (calcScaledPrice(value) == scaledValue) { 
      return value; 
     } 
    } 
    return "not found"; 
} 

calcValue(2) // 200 
calcValue(50) // 5000 
0

你的程序变为从在范围[0..10000000]的值的价格,以在范围[0..20]的整数,使用线性规则和舍入。然后(单调增长)查找表返回应用于原始值的百分比。

你得到的是一个分段线性函数,在百分比变化的地方是不连续的。例如,值6249999和6250000将映射到百分比0.01和0.012,产生输出62499,99和75000.在62499,99和75000之间没有scaledValue对应于任何Value

0

由于Math.round()由于您将域中的许多值映射到相同的值,因此您的函数不是双射。此时,您仍然可以检索给定缩放值的一系列值。

相关问题