Search code examples
c#mathrecursionfuncanonymous-recursion

How to create a big array of Func's representing a Vandermonde system in C#?


I am trying to create a big Vandermonde array of Func's. I can create a 4x3 system like this:

Func<double[], double>[] vandermondeSystem =
{
    x =>  x[0]*Math.Pow(1, 0) + x[1]*Math.Pow(1, 1) + x[2]*Math.Pow(1, 2),
    x =>  x[0]*Math.Pow(2, 0) + x[1]*Math.Pow(2, 1) + x[2]*Math.Pow(2, 2),
    x =>  x[0]*Math.Pow(3, 0) + x[1]*Math.Pow(3, 1) + x[2]*Math.Pow(3, 2),
    x =>  x[0]*Math.Pow(4, 0) + x[1]*Math.Pow(4, 1) + x[2]*Math.Pow(4, 2)
}

But it's infeasible to write big (say 100x50) systems like this, so I think I need to use some kind of looping or recursion but I couldn't figure how.

This page explains how to create an anonymous recursion for implementing the Fibonacci function but I couldn't figure out how to utilize the method explained there.


Solution

  • Based on your current code, you can easily modify it to support bigger systems of size 100x50 and so on. How about something like this:

    Func<double[], double>[] bigVandermondeSystem = new Func<double[], double>[100];
    
    // Constructing a 100 x 50 Vandermonde System
    for (int i = 0; i < 100; i++)
    {
        var i1 = i;
        bigVandermondeSystem[i] = x => Enumerable
            .Range(0, 50)
            .Sum(number => x[number] * Math.Pow(i1 + 1, number));
    }