private void button_start_Click(object sender, EventArgs e) { if (Convert.ToDouble(textBox_borderAccuracy.Text) < Convert.ToDouble(textBox_eps.Text)) { System.Windows.MessageBox.Show("Лучше так не делать, точность выхода на границу меньше, чем контроль локальной погрешности!"); return; } CounterOfTests++; dataGridView_MetodInfo.Rows.Clear(); dataGridView_TaskInfo.Rows.Clear(); Function Func = new Function(); Func.SetFunction(Convert.ToDouble(textBox_alfa.Text), Convert.ToDouble(textBox_sigma.Text)); FunkDelegate function = Func.FunctionValue; TrueSolution trueSolution = new TrueSolution(Convert.ToDouble(textBox_alfa.Text), Convert.ToDouble(textBox_sigma.Text), Convert.ToDouble(textBox_u_0.Text)); Runge_Kutta_2 RK_2 = new Runge_Kutta_2(); RK_2.Init(Convert.ToDouble(textBox_x_0.Text), Convert.ToDouble(textBox_u_0.Text), Convert.ToDouble(textBox_h.Text), Convert.ToDouble(textBox_eps.Text), Convert.ToDouble(textBox_borderAccuracy.Text), Convert.ToInt32(textBox_max_iter.Text), function, checkBox_StepControl.Checked); RK_2.Run(); cartesianChart1.Series.Add(new LineSeries { Title = "Численное решение #" + Convert.ToString(CounterOfTests), Values = new ChartValues <ObservablePoint>(RK_2 .GetPoints() .Select(_ => new ObservablePoint(_.X, _.V))), PointGeometrySize = 5 }); List <MetodInfo> metodInfos = RK_2.GetMetodInfos(); metodInfos.ForEach(_ => dataGridView_MetodInfo.Rows.Add (_.Iteration, _.H, _.X, _.V, _.UHalf, _.V - _.UHalf, _.S, _.e, _.UCorr, _.V, trueSolution.FunctionValue(_.X), Math.Abs(trueSolution.FunctionValue(_.X) - _.V).ToString("F8"), _.CountMinusH, _.CountPlusH)); dataGridView_MetodInfo.AutoResizeColumns(); TaskInfo taskInfo = new TaskInfo(CounterOfTests, Convert.ToDouble(textBox_alfa.Text), Convert.ToDouble(textBox_sigma.Text), Convert.ToDouble(textBox_x_0.Text), Convert.ToDouble(textBox_u_0.Text), Convert.ToDouble(textBox_h.Text), Convert.ToDouble(textBox_eps.Text), Convert.ToInt32(textBox_max_iter.Text)); dataGridView_TaskInfo.Rows.Add(taskInfo.Number, taskInfo.Alfa, taskInfo.Sigma, taskInfo.X0, taskInfo.U0, taskInfo.h0, taskInfo.e, taskInfo.Max_iteration); listExperimentInfos.Add(new ExperimentInfo(taskInfo, metodInfos)); comboBox_TaskSelector.Items.Add("Тест №" + Convert.ToString(CounterOfTests)); richTextBox_log.AppendText(" Время вытекания жидкости в Тесте №" + Convert.ToString(CounterOfTests) + ": " + RK_2.GetResultTime() + " секунд.\n"); }
static void Main(string[] args) { Console.WriteLine("1: x+0.5");//выводим перечень функций Console.WriteLine("2: x^2+12x+7.5"); Console.WriteLine("3: x^3-5"); Console.WriteLine("4: sin(x)"); Console.WriteLine("5: x*cos(x)"); int ch; //переменная для выбора функции FunkDelegate funk = Funk1; //делегат функции do { Console.WriteLine("Select an option"); //выводим подсказку для выбора функции ch = Convert.ToInt32(Console.ReadLine()); //выбираем функцию switch (ch) { case 1: funk = Funk1; break; //в зависимости от выбора назначаем функцию делегату case 2: funk = Funk2; break; case 3: funk = Funk3; break; case 4: funk = Funk4; break; case 5: funk = Funk5; break; default: Console.WriteLine("Invalid function selection"); break; //если выбрали цифру, которой не соответствует никакая функция } } while ((ch < 1) || (ch > 5)); //повторяем пока не выберем нормальную функцию Console.WriteLine("Lower limit of integration"); //вводим верхний, нижний пределы и точность интегрирования double a = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Upper integration limit"); double b = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Required accuracy"); double eps = Convert.ToDouble(Console.ReadLine()); double[] result = PramLeft(funk, a, b, eps); //интегрируем левыми прямоугольниками Console.WriteLine("Methos of left rectangles"); //показываем результаты Console.WriteLine("Value: " + result[0]); Console.WriteLine("Number of partitions: " + result[1]); Console.WriteLine("The accuracy obtained: " + result[2]); result = PramRight(funk, a, b, eps); //интегрируем правыми прямоугольниками Console.WriteLine("Methos of rigth rectangles"); //показываем результаты Console.WriteLine("Value: " + result[0]); Console.WriteLine("Number of partitions: " + result[1]); Console.WriteLine("The accuracy obtained: " + result[2]); result = PramMiddle(funk, a, b, eps); //интегрируем средними прямоугольниками Console.WriteLine("Methos of middle rectangles"); //показываем результаты Console.WriteLine("Value: " + result[0]); Console.WriteLine("Number of partitions: " + result[1]); Console.WriteLine("The accuracy obtained: " + result[2]); Console.ReadLine(); }
private int steps = 0; // число шагов в данный момент public void Init(double _x0, double _u0, double _h, double _eps, double _borderAccuracy, int _maxSteps, FunkDelegate _f, bool _flagIsHControl) { currentPoint = new Point(_x0, _u0); h = _h; eps = _eps; borderAccuracy = _borderAccuracy; f = _f; maxSteps = _maxSteps; flagStepControl = _flagIsHControl; listOfPoints.Add(currentPoint); listIfMetodInfo.Add(new MetodInfo(steps, 0, _x0, _u0, 0, 0, 0, 0, 0, 0, 0, 0)); steps++; }
protected int n; // число шагов public void Init(FunkDelegate _f, double left, double right, int _n) { f = _f; a = left; b = right; n = _n; BestTrial = new SearchInformationElement(); list_of_Trials = new List <SearchInformationElement>(); list_of_test_points = new List <double>(); measurement_counterer = 0; list_of_interval_characteristic = new List <double>(); index_Max_Interval_Characteristic = 0; }
private void DrawObjectiveFunction(object sender, FunkDelegate f) { var myChart = sender as Chart; myChart.Series.Clear(); Series SeriesOfPoints = new Series("Целевая функция"); SeriesOfPoints.ChartType = SeriesChartType.Line; SeriesOfPoints.Color = Color.Black; SeriesOfPoints.BorderWidth = 1; for (double i = Convert.ToDouble(textBox_a.Text); i < Convert.ToDouble(textBox_b.Text); i = i + 0.01) { SeriesOfPoints.Points.AddXY(i, f(i)); } myChart.Series.Add(SeriesOfPoints); }
private void button_drow_function_Click(object sender, EventArgs e) { try { Function Func = new Function(); Func.SetFunction(Convert.ToDouble(textBox_A_param.Text), Convert.ToDouble(textBox_B_param.Text), Convert.ToDouble(textBox_C_param.Text), Convert.ToDouble(textBox_D_param.Text)); FunkDelegate function = Func.FunctionValue; DrawObjectiveFunction(chart_function, function); richTextBox_log.AppendText("График построен.\n"); } catch (Exception error) { MessageBox.Show(error.Message); } }
static double[] PramLeft(FunkDelegate funk, double aa, double bb, double eps) //левые прямоугольники { double a, b; //переменные для границ интегрирования if (bb > aa) { a = aa; b = bb; } //проверка на то, что верхняя граница меньше нижней else { a = bb; b = aa; } double r1, r2, h; //два результата интегрирования с разными разбиениями и шаг интегрирования int n = 10; //число разбиений r2 = 0; //обнуляем перед суммированием h = (b - a) / n; //считаем шаг for (int i = 0; i < n; i++) { r2 += funk(a + i * h) * h; //суммируем по промежутками методом левых прямоугольников (по формуле) } r1 = r2 - 10 * eps; //задаем начальное значение чтобы наверняка войти в цикл while (Math.Abs(r2 - r1) / 3 > eps) //пока не достигнем нужной точности { r1 = r2; //запоминаем предыдущее значение r2 = 0; //зануляем перед суммированием n *= 2; //увеличиваем разбиение в два раза h = (b - a) / n; //считаем шаг для разбиения for (int i = 0; i < n; i++) { r2 += funk(a + i * h) * h; //суммируем по промежутками методом левых прямоугольников (по формуле) } } double[] res = new double[3]; //массив для вывода всех результатов res[0] = r2; //результат интегрирования res[1] = n; //число разбиений res[2] = Math.Abs(r2 - r1) / 3; //достигнутая точность return(res); }
private void button_start_Click(object sender, EventArgs e) { //try //{ Function Func = new Function(); Func.SetFunction(Convert.ToDouble(textBox_A_param.Text), Convert.ToDouble(textBox_B_param.Text), Convert.ToDouble(textBox_C_param.Text), Convert.ToDouble(textBox_D_param.Text)); FunkDelegate function = Func.FunctionValue; DrawObjectiveFunction(chart_function, function); chart_points.Series.Clear(); chart_points.Legends.Clear(); chart_points.ChartAreas[0].AxisX.Enabled = AxisEnabled.False; // отображение подписей по ОХ в точках Series SeriesOfPointsTests = new Series("Испытания"); SeriesOfPointsTests.ChartType = SeriesChartType.Line; SeriesOfPointsTests.Color = Color.Red; SeriesOfPointsTests.BorderWidth = 1; double y = 0; double y_delta = 0.1; // шаг вверх для визуализации точек испытаний SeriesOfPointsTests.Points.AddXY(Convert.ToDouble(textBox_a.Text), 0); SeriesOfPointsTests.Points.AddXY(Convert.ToDouble(textBox_b.Text), 0); if (radioButton_uniform_search.Checked) { if (!radioButton_iteration_stop.Checked && !radioButton_accuracy_stop.Checked) { richTextBox_log.AppendText("Не выбрано условие остановки.\n"); } if (radioButton_accuracy_stop.Checked) { UniformSearchMethodEps usm_eps = new UniformSearchMethodEps(); usm_eps.Init(function, Convert.ToDouble(textBox_a.Text), Convert.ToDouble(textBox_b.Text), Convert.ToDouble(textBox_accuracy.Text)); usm_eps.Run(); for (int i = 0; i < usm_eps.list_of_test_points.Count; i++) { SeriesOfPointsTests.Points.AddXY(usm_eps.list_of_test_points[i], y); y = y + y_delta; } richTextBox_log.AppendText("Равномерная сетка по точности: \n"); richTextBox_log.AppendText(" Min x = " + usm_eps.BestTrial.GetPoint() + "\n"); richTextBox_log.AppendText(" Min Func = " + usm_eps.BestTrial.GetFunctionValue() + "\n"); //richTextBox_log.AppendText(" Интервал неопределенности = " + usm.uncertainty_interval + "\n"); richTextBox_log.AppendText(" Погрешность = " + usm_eps.error + "\n"); richTextBox_log.AppendText(" Число измерений функции = " + usm_eps.measurement_counterer + "\n"); richTextBox_log.AppendText("\n"); } if (radioButton_iteration_stop.Checked) { UniformSearchMethod usm = new UniformSearchMethod(); usm.Init(function, Convert.ToDouble(textBox_a.Text), Convert.ToDouble(textBox_b.Text), Convert.ToInt32(textBox_number_steps.Text)); usm.Run(); for (int i = 0; i < usm.list_of_test_points.Count; i++) { SeriesOfPointsTests.Points.AddXY(usm.list_of_test_points[i], y); y = y + y_delta; } richTextBox_log.AppendText("Равномерная сетка по шагам: \n"); richTextBox_log.AppendText(" Min x = " + usm.BestTrial.GetPoint() + "\n"); richTextBox_log.AppendText(" Min Func = " + usm.BestTrial.GetFunctionValue() + "\n"); //richTextBox_log.AppendText(" Интервал неопределенности = " + usm.uncertainty_interval + "\n"); richTextBox_log.AppendText(" Погрешность = " + usm.error + "\n"); richTextBox_log.AppendText(" Число измерений функции = " + usm.measurement_counterer + "\n"); richTextBox_log.AppendText("\n"); } } if (radioButton_piyavsky.Checked) { if (!radioButton_iteration_stop.Checked && !radioButton_accuracy_stop.Checked) { richTextBox_log.AppendText("Не выбрано условие остановки.\n"); } if (radioButton_accuracy_stop.Checked) { PiyavskyMethod pm = new PiyavskyMethod(); pm.Init(function, Convert.ToDouble(textBox_a.Text), Convert.ToDouble(textBox_b.Text), Convert.ToDouble(textBox_r_piyavsky.Text), Convert.ToDouble(textBox_accuracy.Text)); pm.Run(); for (int i = 0; i < pm.list_of_test_points.Count; i++) { SeriesOfPointsTests.Points.AddXY(pm.list_of_test_points[i], y); y = y + y_delta; } richTextBox_log.AppendText("Пиявский c остановкой по точности: \n"); richTextBox_log.AppendText(" Min x = " + pm.BestTrial.GetPoint() + "\n"); richTextBox_log.AppendText(" Min Func = " + pm.BestTrial.GetFunctionValue() + "\n"); richTextBox_log.AppendText(" Число измерений функции = " + pm.measurement_counterer + "\n"); richTextBox_log.AppendText("\n"); } if (radioButton_iteration_stop.Checked) { PiyavskyMethodFixed pm = new PiyavskyMethodFixed(); pm.Init(function, Convert.ToInt32(textBox_number_steps.Text), Convert.ToDouble(textBox_a.Text), Convert.ToDouble(textBox_b.Text), Convert.ToDouble(textBox_r_piyavsky.Text)); pm.Run(); for (int i = 0; i < pm.list_of_test_points.Count; i++) { SeriesOfPointsTests.Points.AddXY(pm.list_of_test_points[i], y); y = y + y_delta; } richTextBox_log.AppendText("Пиявский с фиксированным числом шагов: \n"); richTextBox_log.AppendText(" Min x = " + pm.BestTrial.GetPoint() + "\n"); richTextBox_log.AppendText(" Min Func = " + pm.BestTrial.GetFunctionValue() + "\n"); richTextBox_log.AppendText(" Число измерений функции = " + pm.measurement_counterer + "\n"); richTextBox_log.AppendText("\n"); } } if (radioButton_strongin.Checked) { if (!radioButton_iteration_stop.Checked && !radioButton_accuracy_stop.Checked) { richTextBox_log.AppendText("Не выбрано условие остановки.\n"); } if (radioButton_accuracy_stop.Checked) { StronginMethod sm = new StronginMethod(); sm.Init(function, Convert.ToDouble(textBox_a.Text), Convert.ToDouble(textBox_b.Text), Convert.ToDouble(textBox_r_piyavsky.Text), Convert.ToDouble(textBox_accuracy.Text)); sm.Run(); for (int i = 0; i < sm.list_of_test_points.Count; i++) { SeriesOfPointsTests.Points.AddXY(sm.list_of_test_points[i], y); y = y + y_delta; } richTextBox_log.AppendText("Стронгин: \n"); richTextBox_log.AppendText(" Min x = " + sm.BestTrial.GetPoint() + "\n"); richTextBox_log.AppendText(" Min Func = " + sm.BestTrial.GetFunctionValue() + "\n"); richTextBox_log.AppendText(" Число измерений функции = " + sm.measurement_counterer + "\n"); richTextBox_log.AppendText("\n"); } if (radioButton_iteration_stop.Checked) { StronginMethodFixed sm = new StronginMethodFixed(); sm.Init(function, Convert.ToInt32(textBox_number_steps.Text), Convert.ToDouble(textBox_a.Text), Convert.ToDouble(textBox_b.Text), Convert.ToDouble(textBox_r_piyavsky.Text)); sm.Run(); for (int i = 0; i < sm.list_of_test_points.Count; i++) { SeriesOfPointsTests.Points.AddXY(sm.list_of_test_points[i], y); y = y + y_delta; } richTextBox_log.AppendText("Стронгин с фиксированным числом шагов: \n"); richTextBox_log.AppendText(" Min x = " + sm.BestTrial.GetPoint() + "\n"); richTextBox_log.AppendText(" Min Func = " + sm.BestTrial.GetFunctionValue() + "\n"); richTextBox_log.AppendText(" Число измерений функции = " + sm.measurement_counterer + "\n"); richTextBox_log.AppendText("\n"); } } chart_points.Series.Add(SeriesOfPointsTests); //chart_function.Series.Add(SeriesOfPointsTests); richTextBox_log.SelectionStart = richTextBox_log.Text.Length; richTextBox_log.ScrollToCaret(); }