我有一个算法来计算目标成本上的产品数量。一个产品的成本不是固定不变的,它要贵10%。如果目标成本比不完全成本更接近,则可能会超过目标成本。
我需要优化代码和排除循环,因为它在高目标成本下是无效的。
这是我使用单元测试(nunit framework)的工作解决方案。
public static int CalculateProductAmountOnCost( double targetCost, double productRate )
{
if ( targetCost <= 0 || productRate <= 0 )
return 1;
var previousCollectedCost = 0.0;
var collectedCost = 0.0;
var amount = 0;
for ( ; collectedCost < targetCost; amount++ )
{
previousCollectedCost = collectedCost;
collectedCost += productRate*Math.Pow( 1.1, amount );
}
if ( targetCost - previousCollectedCost < collectedCost - targetCost )
amount -= 1;
return Math.Max( 1, amount );
}
[Test]
[TestCase( 9, 2, 4 )]
[TestCase( 7, 2, 3 )]
[TestCase( 0, 2, 1 )]
[TestCase( 9, 0, 1 )]
[TestCase( 4.5, 0.2, 12 )]
public void TradeDealHelper_CalculateProductAmountOnGemCostTest( double targetCost, double productRate,
int expectedAmount )
{
var actualAmount = TradeDealHelper.CalculateProductAmountOnCost( targetCost, productRate );
Assert.AreEqual( expectedAmount, actualAmount );
}发布于 2017-07-13 11:21:40
public static int CalculateProductAmountOnCost2(double targetCost, double productRate)
{
if (targetCost <= 0 || productRate <= 0)
return 1;
var amount = (int)Math.Floor(Math.Log(((targetCost / (productRate * 10)) + 1), 1.1) - 1);
var lowerCost = productRate * 10 * (Math.Pow(1.1, amount + 1) - 1);
var upperCost = productRate * 10 * (Math.Pow(1.1, amount + 2) - 1);
if (targetCost - lowerCost > upperCost - targetCost)
amount++;
return Math.Max(1, amount + 1);
}你可以用一点数学。下面的内容基本上是数学方面的东西,而不是代码。
你的总费用是:
totalCost = productRate + productRate * 1.1 + productRate * (1.1 ^ 2) + ... + productRate * (1.1 ^ n)可以改写为:
totalCost = productRate * (1 + 1.1 + 1.1 ^ 2 + ... 1.1 ^ n)有一个公式可以计算出这一数额:
1 + a + a ^ 2 + ... a ^ n = (a ^ (n + 1) - 1) / (a - 1)所以你现在的总成本是:
totalCost = productRate * ((1.1 ^ (n + 1) - 1) / (1.1 - 1))
totalCost = productRate * 10 * (1.1 ^ (n + 1) - 1)我们应用最后一个公式为您的n查找targetCost,我们得到:
n = Math.Log((targetCost / (productRate * 10)) + 1, 1.1) - 1(这是基数1.1的对数)
代码正在应用这些公式。
https://stackoverflow.com/questions/45077134
复制相似问题