Skip to content

Instantly share code, notes, and snippets.

@yutopio
Created May 24, 2013 14:54
Show Gist options
  • Save yutopio/5644098 to your computer and use it in GitHub Desktop.
Save yutopio/5644098 to your computer and use it in GitHub Desktop.
Neville interpolation
using System;
class Program
{
static void Main()
{
var funcs = new Func<double, double>[8];
funcs[0] = x => Math.Exp(x);
funcs[1] = x => Math.Log(x);
funcs[2] = x => 1 + x + x * x;
for (var i = 3; i <= 7; i++)
{
var j = i;
funcs[j] = x => funcs[j - 1](x) + Math.Pow(x, j);
}
var values = new double[8][,];
for (var j = 0; j < 8; j++)
{
values[j] = new double[6, 2];
for (var i = 5; i <= 10; i += 1)
values[j][i - 5, 1] = funcs[j](values[j][i - 5, 0] = (i / 10d));
}
Console.WriteLine("Original value\t\tNeville interpolation\tDifference rate");
for (var i = 0; i < 8; i++)
{
var nev = Neville(values[i]);
var f = funcs[i](.75);
var n = nev(.75);
Console.WriteLine("{0}\t{1}\t{2}", f.ToString("e10"), n.ToString("e10"), Math.Abs((n - f) / f).ToString("e10"));
}
}
static Func<double, double> Neville(double[,] values)
{
var len = values.GetLength(0);
var funcs = new Func<double, double>[len, len];
for (var i = 0; i < len; i++)
{
var j = i;
funcs[j, j] = x => values[j, 1];
}
for (var i = 1; i < len; i++)
for (var j = 0; j < len - i; j++)
{
var k = j;
var l = j + i;
funcs[k, l] = x => ((x - values[l, 0]) * funcs[k, l - 1](x) + (values[k, 0] - x) * funcs[k + 1, l](x)) / (values[k, 0] - values[l, 0]);
}
return funcs[0, len - 1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment