.NET 4.x Парсинг и вычисление выражения - C#

Узнай цену своей работы

Формулировка задачи:

Пожалуйста помогите понять, как написать код в компоненте на С# для решения уравнений c одной переменной Методом Ньютона. Не пойму как сделать так, чтобы можно было любую функцию с одной переменной с клавиатуры вводить, и чтобы программа её считывала и находила первую и вторую производные. Буду очень благодарна за помощь.

Решение задачи: «.NET 4.x Парсинг и вычисление выражения»

textual
Листинг программы
  1. using System;
  2. using System.CodeDom.Compiler;
  3. using System.Reflection;
  4. using System.Windows.Forms;
  5. using Microsoft.CSharp;
  6.  
  7. namespace WindowsFormsApplication280
  8. {
  9.     public partial class Form1 : Form
  10.     {
  11.         private TextBox tbFunc;
  12.         private TextBox tbX;
  13.         private TextBox tbResult;
  14.  
  15.         public Form1()
  16.         {
  17.             InitializeComponent();
  18.  
  19.             tbFunc = new TextBox {Parent = this, Top = 20, Text = "x*x = 1 - x"};
  20.             new Label { Parent = this, Top = 5, Text = "Function" };
  21.             tbX = new TextBox {Parent = this, Top = 60, Text = "1"};
  22.             new Label { Parent = this, Top = 45, Text = "First approximation" };
  23.             tbResult = new TextBox { Parent = this, Top = 100, ReadOnly = true };
  24.             new Label { Parent = this, Top = 85, Text = "Result" };
  25.  
  26.             new Button { Parent = this, Top = 20, Left = 150, Text = "Calc" }.Click += bt_Click;
  27.         }
  28.  
  29.  
  30.         void bt_Click(object sender, EventArgs e)
  31.         {
  32.             var calculator = new ExpressionCalculator();
  33.             var parts = tbFunc.Text.Split('=');
  34.             var expression = string.Format("({0}) - ({1})", parts[0], parts[1]);
  35.             calculator.Compile(expression);
  36.  
  37.             var solver = new NewtonSolver();
  38.             var res = solver.Solve(x => calculator.Calculate(x), double.Parse(tbX.Text));
  39.             tbResult.Text = res.ToString("N5");
  40.         }
  41.     }
  42.  
  43.     public class ExpressionCalculator
  44.     {
  45.         private MethodInfo mi;
  46.  
  47.         public void Compile(string expression)
  48.         {
  49.             string source =
  50. @"
  51.  using System;
  52.  
  53.  public static class Calculator
  54.  {
  55.    public static double Calc(double x)
  56.    {
  57.      return %expression%;
  58.    }
  59.  }".Replace("%expression%", expression);
  60.  
  61.             // Настройки компиляции
  62.             var compilerParams = new CompilerParameters { GenerateInMemory = true };
  63.             // Компиляция
  64.             var results = new CSharpCodeProvider().CompileAssemblyFromSource(compilerParams, source);
  65.             //обработка ошибок
  66.             if (results.Errors.Count > 0)
  67.                 throw new Exception(results.Errors[0].ErrorText);
  68.             //вычисляем
  69.             var calculator = results.CompiledAssembly.GetType("Calculator");
  70.             mi = calculator.GetMethod("Calc");
  71.         }
  72.  
  73.         public double Calculate(double x)
  74.         {
  75.             return (double)mi.Invoke(null, new object[] { x });
  76.         }
  77.     }
  78.  
  79.     public class NewtonSolver
  80.     {
  81.         public double Epsylon = 0.0001d;
  82.  
  83.         public double Solve(Func<double, double> func, double firstApprox)
  84.         {
  85.             var prev = firstApprox - Epsylon*2;
  86.             var x = firstApprox;
  87.  
  88.             while(Math.Abs(x - prev) > Epsylon)
  89.             {
  90.                 prev = x;
  91.                 //производная
  92.                 var dx = 0.001d;
  93.                 var y = func(x);
  94.                 var dy = func(x + dx) - y;
  95.                 var deriv = dy/dx;
  96.  
  97.                 //формула Ньютона
  98.                 x = x - y/deriv;
  99.             }
  100.  
  101.             return x;
  102.         }
  103.     }
  104. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

8   голосов , оценка 3.875 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы