Advertisement
Slavik9510

Untitled

Dec 6th, 2022
743
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.27 KB | None | 0 0
  1. using System;
  2.  
  3. namespace Lagrange_Interpolation
  4. {
  5.  
  6.     class Program
  7.     {
  8.         class Data
  9.         {
  10.             private static int length = 0;
  11.             public double x, y;
  12.             public Data(double x, double y)
  13.             {
  14.                 this.x = x;
  15.                 this.y = y;
  16.                 length++;
  17.             }
  18.             ~Data()
  19.             {
  20.                 length--;
  21.             }
  22.             public static int GetLength()
  23.             {
  24.                 return length;
  25.             }
  26.         };
  27.         static double interpolate(Data[] f, double x0)
  28.         {
  29.             Console.WriteLine("************************");
  30.             Console.WriteLine("Lagrange's Interpolation");
  31.             Console.WriteLine("************************");
  32.             Console.WriteLine($"X0 = {x0}\n");
  33.  
  34.             double result = 0;
  35.             int n = Data.GetLength();
  36.  
  37.             for (int i = 0; i < n; i++)
  38.             {
  39.                 double diagonal = f[i].y;
  40.                 for (int j = 0; j < n; j++)
  41.                 {
  42.                     if (j != i)
  43.                         diagonal *= (x0 - f[j].x) / (f[i].x - f[j].x);
  44.                 }
  45.                 Console.WriteLine($"L[{i}] = {diagonal:F8}");
  46.                 result += diagonal;
  47.             }
  48.             Console.WriteLine();
  49.             return result;
  50.         }
  51.         static void Main(string[] args)
  52.         {
  53.        
  54.             Console.Write("К-сть точок: ");
  55.             int n = int.Parse(Console.ReadLine());
  56.             if (n < 2)
  57.             {
  58.                 Console.WriteLine("Error");
  59.                 Environment.Exit(1);
  60.             }
  61.             Data[] f = new Data[n];
  62.             for (int i = 0; i < n; i++)
  63.             {
  64.                 //Точки ввдоити через пробіл(розділовий знак кома)
  65.                 Console.WriteLine($"Введiть {i + 1} точку: ");
  66.                 string[] c = Console.ReadLine().Split(' ');
  67.                 f[i] = new Data(double.Parse(c[0]), double.Parse(c[1]));
  68.             }
  69.             Console.Write("Введiть x0: ");
  70.             double x0 = double.Parse(Console.ReadLine());
  71.             Console.WriteLine($"Value of f({x0}) = {interpolate(f, x0)}");
  72.         }
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement