我有一个C#方法,它将一个数字的值从一个区间投影到一个目标区间。
例如:我们有一个-1000和9000的区间和5000的值;如果我们想突出这个值的0..100的间隔,我们得到60使C#算法更有效
这里是方法:
/// <summary>
/// Projects a value to an interval
/// </summary>
/// <param name="val">The value that needs to be projected</param>
/// <param name="min">The minimum of the interval the value comes from</param>
/// <param name="max">The maximum of the interval the value comes from</param>
/// <param name="intervalTop">The minimum of the interval the value will
/// be projected to</param>
/// <param name="intervalBottom">The maximum of the interval the value will
/// be projected to</param>
/// <returns>Projected value</returns>
public decimal ProjectValueToInterval(decimal val,
decimal min,
decimal max,
decimal intervalBottom,
decimal intervalTop)
{
decimal newMin = Math.Min(0, min);
decimal valueIntervalSize = Math.Abs(max - newMin);
decimal targetIntervalSize = Math.Abs(intervalTop - intervalBottom);
decimal projectionUnit = targetIntervalSize/valueIntervalSize;
return (val * projectionUnit) + Math.Abs((newMin * projectionUnit));
}
这种方法需要被称为千值。
我想知道是否有更有效的方式在C#中做到这一点?如果是的话,你有什么改变建议?
为什么“decimal newMin = Math.Min(0,min);”?对于任何积极的最低要求,这不会给你错误的答案吗? – VVS 2008-12-04 10:16:28
你是对的,Math.Min(0,min)使得数值范围从0;我忘了拿出这个,但它不影响这个问题... – Germstorm 2008-12-04 13:27:56