using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CsTest
{ //可以确定的是n个插值点的拉格朗日多项式的最大次数为n
public class Ploy //多项式
{
public double[] a;//系数,指数即索引值
public Ploy(int n = 1)
{
a = new double[n]; //当未给数组中的每一项赋值时,其值为0
}
public static Ploy operator +(Ploy a1, Ploy b1)//多项式a1和b1的项数相同
{
Ploy p = new Ploy(a1.a.Length);
for (int i = 0; i < a1.a.Length; i++)
{
p.a[i] = a1.a[i] + b1.a[i];//系数相加
}
return p;
}
public static Ploy operator *(Ploy a1, Ploy b1)
{
Ploy p = new Ploy(a1.a.Length);
for (int i = 0; i < a1.a.Length; i++)
{
if (a1.a[i] == 0)
{
continue; //此项系数为0
}
for (int j = 0; j < a1.a.Length; j++)
{
if (b1.a[j] == 0)//此项系数为0
{
continue;
}
if (i + j > a1.a.Length)
{
Console.WriteLine("运算出现错误");
break;
}
p.a[i + j] += a1.a[i] * b1.a[j];
}
}
return p;
}
}
class Program
{
static void Main(string[] args)
{
int n = 4;
//获取文件中的x值得数量并赋给n
//int[] X = new int[n]; //横坐标数组
//int[] Y = new int[n]; //纵坐标数组
int[] X = { 0, 1, 2, 3 };
int[] Y = { 2, -1, 4, 3 };
Ploy lag = new Ploy(n);//拉格朗日多项式
for (int i = 0; i < n; i++)
{
Ploy py = new Ploy(X.Length);
py.a[0] = Y[i];
Ploy px = new Ploy(X.Length);
px.a[0] = 1;
for (int k = 0; k < X.Length; k++)
{
if (i != k)
{
px.a[0] *= X[i] - X[k];
}
}
py.a[0] /= px.a[0];
Ploy mul = new Ploy(n);
mul.a[0] = 1;
for (int j = 0; j < n; j++)
{
Ploy temp=new Ploy(n);
temp.a[1]=1;
Ploy temp2=new Ploy(n);
if(i==j)
{
continue;
}
temp2.a[0]=-X[j];
mul *= temp + temp2;
}
lag += py * mul;
}
//输出拉格朗日多项式
for(int i=n-1;i>=0;i--)
{
if (lag.a[i] == 0)
continue;
Console.Write("{0}x^{1}+",lag.a[i],i);
}
}
}
}
拉格朗日多项式
本文转载:CSDN博客