1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 namespace CsTest 6 { //可以确定的是n个插值点的拉格朗日多项式的最大次数为n 7 public class Ploy //多项式 8 { 9 public double[] a;//系数,指数即索引值 10 public Ploy(int n = 1) 11 { 12 a = new double[n]; //当未给数组中的每一项赋值时,其值为0 13 } 14 public static Ploy operator +(Ploy a1, Ploy b1)//多项式a1和b1的项数相同 15 { 16 Ploy p = new Ploy(a1.a.Length); 17 for (int i = 0; i < a1.a.Length; i++) 18 { 19 p.a[i] = a1.a[i] + b1.a[i];//系数相加 20 } 21 return p; 22 } 23 public static Ploy operator *(Ploy a1, Ploy b1) 24 { 25 Ploy p = new Ploy(a1.a.Length); 26 for (int i = 0; i < a1.a.Length; i++) 27 { 28 if (a1.a[i] == 0) 29 { 30 continue; //此项系数为0 31 } 32 for (int j = 0; j < a1.a.Length; j++) 33 { 34 if (b1.a[j] == 0)//此项系数为0 35 { 36 continue; 37 } 38 if (i + j > a1.a.Length) 39 { 40 Console.WriteLine("运算出现错误"); 41 break; 42 } 43 p.a[i + j] += a1.a[i] * b1.a[j]; 44 } 45 } 46 return p; 47 } 48 } 49 class Program 50 { 51 static void Main(string[] args) 52 { 53 int n = 4; 54 //获取文件中的x值得数量并赋给n 55 //int[] X = new int[n]; //横坐标数组 56 //int[] Y = new int[n]; //纵坐标数组 57 int[] X = { 0, 1, 2, 3 }; 58 int[] Y = { 2, -1, 4, 3 }; 59 Ploy lag = new Ploy(n);//拉格朗日多项式 60 for (int i = 0; i < n; i++) 61 { 62 Ploy py = new Ploy(X.Length); 63 py.a[0] = Y[i]; 64 Ploy px = new Ploy(X.Length); 65 px.a[0] = 1; 66 for (int k = 0; k < X.Length; k++) 67 { 68 if (i != k) 69 { 70 px.a[0] *= X[i] - X[k]; 71 } 72 } 73 py.a[0] /= px.a[0]; 74 Ploy mul = new Ploy(n); 75 mul.a[0] = 1; 76 for (int j = 0; j < n; j++) 77 { 78 Ploy temp=new Ploy(n); 79 temp.a[1]=1; 80 Ploy temp2=new Ploy(n); 81 if(i==j) 82 { 83 continue; 84 } 85 temp2.a[0]=-X[j]; 86 mul *= temp + temp2; 87 } 88 lag += py * mul; 89 } 90 //输出拉格朗日多项式 91 for(int i=n-1;i>=0;i--) 92 { 93 if (lag.a[i] == 0) 94 continue; 95 Console.Write("{0}x^{1}+",lag.a[i],i); 96 } 97 } 98 } 99 }