Answer the question
In order to leave comments, you need to log in
The program throws an IndexOutOfRangeException error. What is the reason and how to fight?
I am currently working on a project that involves solving systems of N equations with N unknowns using Newton's method. There is a class "system of equations":
public class EquationsSystem
{
/// <summary>
/// Функции, определяющие внешний вид уравнений системы. Каждое уравнение имеет вид F(x1,x2,...xN) = 0.
/// </summary>
public List<Func<double[], double[], double>> EquationFunctions { get; set; }
/// <summary>
/// Коэффициенты в уравнениях системы.
/// </summary>
public List<double[]> EquationsCoefficients { get; set; }
}
static double EquationFunction(double[] x, double[] beta, int inxX)
{
double equationValue = 0.0;
int qVars= x.Length;
equationValue = beta[0] + beta[1] * x[inxX] + (beta[2] / (qVars-1)) * (x.Sum() - x[inxX]);
return equationValue;
}
static EquationsSystem CreateEquationsSystem(List<double[]> lstCoeffsInEquations)
{
int qEquations = lstCoeffsInEquations.Count;
int qCoeffs = lstCoeffsInEquations[0].Length;
EquationsSystem system = new EquationsSystem()
{
EquationFunctions = new List<Func<double[], double[], double>>(),
EquationsCoefficients = new List<double[]>(),
};
for (int i = 0; i < qEquations; i++)
{
system.EquationFunctions.Add(new Func<double[], double[], double>((x, beta) =>
EquationFunction(x, beta, i));
}
for (int i = 0; i < qEquations; i++)
{
system.EquationsCoefficients.Add(new double[qCoeffs]);
for (int j = 0; j < qCoeffs; j++)
{
system.EquationsCoefficients[i][j] = lstCoeffsInEquations[i][j];
}
}
return system;
}
public static double GetDerivative(Func<double[], double[], double> function, double[] variables, int inxVariable, double[] coefficients, double eps)
{
...
//Остальная часть не важна
double f = function(variables, coefficients);
...
}
...
for (int i = 0; i < qEquations; i++)
{
system.EquationFunctions.Add(new Func<double[], double[], double>((x, beta) =>
EquationFunction(x, beta, i));
}
...
, static double EquationFunction(double[] x, double[] beta, int inxX)
{
double equationValue = 0.0;
int qVars= x.Length;
equationValue = beta[0] + beta[1] * x[inxX] + (beta[2] / (qVars-1)) * (x.Sum() - x[inxX]);
return equationValue;
}
Answer the question
In order to leave comments, you need to log in
Very similar to the problem of improper use of closures. Try like this:
for (int i = 0; i < qEquations; i++)
{
int index = i;
system.EquationFunctions.Add(new Func<double[], double[], double>((x, beta) =>
EquationFunction(x, beta, index)); // <-- index вместо i
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question