The following code is very repetitive:
public static double Interpolate(double x1, double y1, double x2, double y2, double x)
{
return y1 + (x - x1) * (y2 - y1) / (x2 - x1);
}
public static decimal Interpolate(decimal x1, decimal y1, decimal x2, decimal y2, decimal x)
{
return y1 + (x - x1) * (y2 - y1) / (x2 - x1);
}
However, my attempt to use generics does not compile:
public static T Interpolate<T>(T x1, T y1, T x2, T y2, T x)
{
return y1 + (x - x1) * (y2 - y1) / (x2 - x1);
}
The error message is as follows:
Error 2 Operator '-' cannot be applied to operands of type 'T' and 'T' C:\Git...\LinearInterpolator.cs
How should I reuse my code?
Edit: fast runtime is important for this modules.
Your current code is fine as it is - possibly the best you can achieve without casting doubles to decimals.
A generic solution is possible, but would involve quite a lot of infrastructure - so much so that it would make things way too complex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With