我有一個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