Oksana_ok

Метод ломаных

Jan 27th, 2021
816
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace ConsoleApp5
  7.  
  8. {
  9. class Program
  10. {
  11. public static double F(double x1, double x2)
  12. {
  13. return 211 * x1 * x1 - 420 * x1 * x2 + 211 * x2 * x2 - 192 * x1 + 50 * x2 -25;
  14. }
  15. public static double F(double[] x)
  16. {
  17. return 211 * x[0] * x[0] - 420 * x[0] * x[1] + 211 * x[1] * x[1] - 192 * x[0] + 50 * x[1] - 25;
  18. }
  19. private static double[] GetGradient(double x1, double x2)
  20. {
  21. double[] result = new double[2];
  22. result[0] = 211 * 2 * x1 - 420 * x2 - 192;
  23. result[1] =  211 * 2 * x2 - 420* x1 + 50;
  24. return result;
  25. }
  26. private static double GetSum(double[] gradient)
  27. {
  28. return Math.Sqrt(gradient[0] * gradient[0] + gradient[1] * gradient[1]);
  29. }
  30. private static double[] GetGradientMethod()
  31. {
  32. double eps = 0.01;
  33. double alpha = 10;
  34. double[] x = new double[2];
  35. x[0] = 10;
  36. x[1] = 10;
  37. double fx = F(x);
  38. double[] GradF = GetGradient(x[0], x[1]);
  39. if (Math.Abs(GetSum(GradF)) <= eps)
  40. {
  41. return x;
  42. }
  43. double fy;
  44. double[] y = new double[2];
  45. while (Math.Abs(GetSum(GradF)) > eps)
  46. {
  47. y[0] = x[0] - alpha * GradF[0];
  48. y[1] = x[1] - alpha * GradF[1];
  49. GradF = GetGradient(x[0], x[1]);
  50. fy = F(y);
  51. if (fy < fx)
  52. {
  53. x = y;
  54. fx = fy;
  55. }
  56. else
  57. {
  58. alpha /= 2;
  59. }
  60. }
  61. Console.WriteLine("Curent: ({0} , {1}\t|\tfunc: {2})", 8.04, -7.76, F(8.04, -7.76));
  62. return x;
  63. }
  64. static void Main(string[] args)
  65. {
  66. double[] X = GetGradientMethod();
  67. Console.WriteLine("Result:\nX:{0} {1}\t\t Y:{2}", X[0], X[1], F(X));
  68. }
  69. }
  70. }
RAW Paste Data