Common table for linear search

I am looking for a generic optimized search object that takes a function f (x) and creates a linear piecewise approximation with customizable parameters for the x range and population intervals.

Obviously, this is not difficult to write, but given that it is useful for many expensive functions (trigger, output, distance), I thought that a common one might already exist. Please let me know.

Another useful feature is to serialize / deserialize the lookup table, since a fairly accurate table of 100,000 points + can take several minutes.

+5
source share
1 answer

, - .NET . - ( C5, ,).

, , #, , . , , - :

// 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 );
    }
}

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)
+4
source

All Articles