Just messing about with F# and I was trying to create a basic Lagrange Interpolation function based on this C# version (copied from a C++ wiki entry):
double Lagrange(double[] pos, double[] val, double desiredPos)
{
double retVal = 0;
for (int i = 0; i < val.Length; ++i)
{
double weight = 1;
for (int j = 0; j < val.Length; ++j)
{
// The i-th term has to be skipped
if (j != i)
{
weight *= (desiredPos - pos[j]) / (pos[i] - pos[j]);
}
}
retVal += weight * val[i];
}
return retVal;
}
The best I could come up with using my limited knowledge of F# and functional programming was:
let rec GetWeight desiredPos i j (pos : float[]) weight =
match i with
| i when j = pos.Length -> weight
| i when i = j -> GetWeight desiredPos i (j+1) pos weight
| i -> GetWeight desiredPos i (j+1) pos (weight * (desiredPos - pos.[j])/(pos.[i] - pos.[j]) )
let rec Lagrange (pos : float[]) (vals : float[]) desiredPos result counter =
match counter with
| counter when counter = pos.Length -> result
| counter -> Lagrange pos vals desiredPos (result + (GetWeight desiredPos counter 0 pos 1.0)* vals.[counter]) (counter+1)
Can someone provide a better/tidier F# version based on the same C# code?