[英]Generic Linear Piecewise Lookup Table
我正在尋找一個通用的優化查找對象,它采用函數f(x)並創建一個線性分段近似,其中包含x的范圍和總體間隔的可配置參數。
顯然這並不難寫,但鑒於它對很多昂貴的函數(trig,yield,distance)很有用,我認為一個通用的函數可能已經存在。 請告訴我。
另一個有用的功能是序列化/反序列化查找表,因為相當精確的100,000點+表可能需要幾分鍾才能構建。
我不相信.NET類庫中直接存在任何內容。 第三方庫中可能存在某些東西( 比如C5 )。
在C#中創建可以接受范圍的函數的泛型版本有點棘手,因為沒有統一類型或接口提供算術運算符。 然而,通過一些創造力,可以制作一些東西:
// generic linear lookup class, supports any comparable type T
public class LinearLookup<T> where T : IComparable<T>
{
private readonly List<T> m_DomainValues = new List<T>();
public LinearLookup( Func<T,T> domainFunc, Func<T,T> rangeFunc,
T lowerBound, T upperBound )
{
m_DomainValues = Range( domainFunc, rangeFunc,
lowerBound, upperBound )
.ToList();
}
public T Lookup( T rangeValue )
{
// this could be improved for numeric types
var index = m_DomainValues.BinarySearch( rangeValue );
if( index < 0 )
index = (-index)-1;
return m_DomainValues[index];
}
private static IEnumerable<T> Range( Func<T,T> domainFunc,
Func<T,T> rangeFunc, T lower, T upper )
{
var rangeVal = lower;
do
{
yield return domainFunc( rangeVal );
rangeVal = rangeFunc( rangeVal );
} while( rangeVal.CompareTo( upper ) < 0 );
}
}
此類將在[lower,upper>]范圍內為函數domainFunc
預計算一組域值。 它使用二進制搜索進行查找 - 允許使用任何類似類型的折衷方案 - 不僅僅是以數字類型構建。 函數rangeFunc
允許增量由外部代碼控制。 因此,這里是Math.Sin
在[0,PI / 2>范圍內的增量為0.01的線性查找:
var sinLookup = new LinearLookup( Math.Sin, x => x + 0.01d, 0, Math.PI/2 );
var lookupPI4 = sinLookup[Math.PI/4]; // fetch the value sin(π/4)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.