using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 数值分析实验报告
{
class Gauss曲线拟合的最小二乘法
{
static void Main()
{
Imput();
wucha();
}
#region 曲线拟合的最小二乘法
private static void Imput()
{
//Console.WriteLine("请输入数据对:");
//string str = Console.ReadLine();
//string[] x = str.Split(')');
//for (int i = 0; i < x.Length; i++)
//{
// double[] Xarr = new double[x.Length];
// double[] Yarr = new double[x.Length];
// string X = x[i].Replace("(", "");
// string[] XI = X.Split(',');
// Xarr[i] = double.Parse(XI[0]);
// Yarr[i] = double.Parse(XI[1]);
// Console.ReadLine();
//}
Console.WriteLine("请输入实验数据的x值:");
string[] x = Console.ReadLine().Split(',');
Console.WriteLine("请输入实验数据的y值:");
string[] y = Console.ReadLine().Split(',');
if (x.Length != y.Length)
{
Console.WriteLine("输入有误,输入的x值与y的值个数不对应!");
return;
}
Console.WriteLine("请输入实验数据各个点的权函数值:");
string[] w = Console.ReadLine().Split(',');
if (x.Length != w.Length)
{
Console.WriteLine("输入有误,输入的w值与x和y的个数不对应!");
return;
}
Console.WriteLine("请输入拟合曲线的最高项次数:");
int n = int.Parse(Console.ReadLine());
Console.WriteLine("实验数据的法方程为:");
double[,] G = new double[n + 1, n + 2];
for (int i = 0; i < n + 1; i++)
{
for (int j = 0; j < n + 2; j++)
{
double X_num = 0;
double Y_Num = 0;
if (i + j == 0)
{
for (int m = 0; m < x.Length; m++)
{
X_num += double.Parse(w[m]);
}
}
else
{
for (int X = 0; X < x.Length; X++)
{
double N = 1;
for (int m = 0; m < i + j; m++)
{
if (m != n + 1)
{
N = N * double.Parse(x[X]);
}
}
X_num += N * double.Parse(w[X]);
if (j == n + 1)
{
double P = 1;
for (int p = 0; p < i; p++)
{
P = P * double.Parse(x[X]);
}
Y_Num += P * double.Parse(w[X]) * double.Parse(y[X]);
}
}
}
if (j == n + 1)
{
G[i, j] = Y_Num;
}
else
{
G[i, j] = X_num;
}
}
}
for (int i = 0; i < n + 1; i++)
{
for (int j = 0; j < n + 2; j++)
{
Console.Write(G[i, j] + "\t");
}
Console.WriteLine();
}
Console.ReadLine();
}
#endregion
private static void wucha()
{
//Console.WriteLine("请输入上面最小二乘法拟合曲线的系数:");
//string[] xishu = Console.ReadLine().Split(' ');
double[] wucha=new double[12];
double[] x = { 0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55 };
double[] f = { 0, 1.27, 2.16, 2.86, 3.44, 3.87, 4.15, 4.37, 4.51, 4.58, 4.62, 4.64 };
for (int i = 0; i < 12; i++)
{
double t1 = x[i];
double t2 = x[i] * x[i];
double t3 = x[i] * x[i] * x[i];
double f1 = 1.34680 + 0.06876 * t1 + 5.30520 * t2 + 1.73252 * t3;
wucha[i] = f1 - f[i];
Console.WriteLine("拟合曲线与在点{0}处的值与真实值的误差为:\n",x[i]);
Console.WriteLine(wucha[i]);
}
Console.ReadLine();
}
}
}
这个程序只是实现了根据已知点来得到方程组的矩阵,解方程组的程序实现还没有实现,不过可以参考上篇高斯列主元法解方程组的程序!
(C#)曲线拟合的最小二乘法
最新推荐文章于 2025-01-14 17:52:17 发布