简体   繁体   中英

weird delegate behavior in C#

So, I have the code which is responsible for Lagrange polynomial calculating. This code is heavily using delegates (fn_result is declared as delegate float fn_result (float x) . The multiplier(x) is properly calculated despite using recursion; however, trying to calculate polynom(x) provides a stack overflow exception. Please could someone tell me why it's so? (Note: polynom(x) is initialized:)

fn_result polynom = x => 0.0f;
for (int i = 0; i != Lagrange_node_points.Length; i++)
{
    fn_result multiplier = x => Lagrange_node_points[i].Y;
    for (int k = 0; k != Lagrange_node_points.Length; k++) // p[k] cycle
        if (k != i)
            multiplier = x => (multiplier(x) * (x - Lagrange_node_points[k].X) / (Lagrange_node_points[i].X - Lagrange_node_points[k].X));
    polynom = y => (polynom(y) + multiplier(y));
}

您在这一行有一个无限递归调用。

polynom = y => (polynom(y) + multiplier(y));

It is exactly as @Eoin says, but both multiplier and polynom are in fact infinite.

Test this example:

public static void Main(string[] args) 
{
  Func<int,int> f = x => x * 2 + 13;
  f = x => f(x) + 1337; // Calling itself, not the original function
  int res = f(1); // Stack overflow!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM