alarray定义了一组在两个相同长度和相同类型的valarray类对象之间的数字计算
比如这里的 最小二乘法拟合直线的程序 就会用到 alarray:
#include <stdlib.h>
#include <iostream>
#include <valarray>
#include <math.h>
{
cout<<"输入变量个数:";
int num =0,tmp
cin>> num;
valarray<double> data_x(num);
valarray<double> data_y(num);
tmp=num;
for(int x=0;x<num;x++)
{
cout<< "输入第"<<x+1<<"项的X:";
cin>>data_x[x];
}
for(int y=0;y<num;y++)
{
cout<<"输入第"<<y+1<<"项的Y:";
cin>> data_y[y];
}
//系数
double A = 0.0;
double B = 0.0;
double C = 0.0;
double D = 0.0;
for(int i =0;i<num;i++)
D = (data_x * data_x).sum();
double i,j,min=data_y[0],max=data_y[0],e=0;
double k = (A * B - data_x.size () * C) / (B * B - data_x.size () * D);
double b = (B * C - A * D) / (B * B - data_x.size () * D);
for(tmp=0;tmp<num;tmp++)
{
i=k*data_x[tmp]+b;
j=i-data_y[tmp];
if(j>e)
{
e=j;
}
if(data_y[tmp]>max)
{
max=data_y[tmp];
min=data_y[tmp];
}
}
//输出
cout<<"Yi各项求和得A="<<A<<endl;
cout<<"Xi各项求和得B="<<B<<endl;
cout<<"Yi*Xi各项求和得C="<<C<<endl;
cout<<"Xi各项平方再和得D="<<D<<endl;
cout<<"斜率k:"<<k<<endl;
cout<<"截距b:"<<b<<endl;
cout<<"最佳拟合直线为:\nY="<<exp(b)<<"*Vp^"<<k<<"\n"<<endl;// 最终结果表示为exp(b)*Vp^k
system("PAUSE");
return 0;
}
比如这里的 最小二乘法拟合直线的程序 就会用到 alarray:
#include <stdlib.h>
#include <iostream>
#include <valarray>
#include <math.h>
using namespace std;
int main(int argc, char *argv[]){
cout<<"输入变量个数:";
int num =0,tmp
cin>> num;
valarray<double> data_x(num);
valarray<double> data_y(num);
tmp=num;
for(int x=0;x<num;x++)
{
cout<< "输入第"<<x+1<<"项的X:";
cin>>data_x[x];
}
for(int y=0;y<num;y++)
{
cout<<"输入第"<<y+1<<"项的Y:";
cin>> data_y[y];
}
//系数
double A = 0.0;
double B = 0.0;
double C = 0.0;
double D = 0.0;
for(int i =0;i<num;i++)
A = log(data_y[i])+A;
B = data_x.sum ();
C = (data_x * log(data_y)).sum();D = (data_x * data_x).sum();
double i,j,min=data_y[0],max=data_y[0],e=0;
double k = (A * B - data_x.size () * C) / (B * B - data_x.size () * D);
double b = (B * C - A * D) / (B * B - data_x.size () * D);
for(tmp=0;tmp<num;tmp++)
{
i=k*data_x[tmp]+b;
j=i-data_y[tmp];
if(j>e)
{
e=j;
}
if(data_y[tmp]>max)
{
max=data_y[tmp];
}
if(data_y[tmp]<min)
{min=data_y[tmp];
}
}
//输出
cout<<"Yi各项求和得A="<<A<<endl;
cout<<"Xi各项求和得B="<<B<<endl;
cout<<"Yi*Xi各项求和得C="<<C<<endl;
cout<<"Xi各项平方再和得D="<<D<<endl;
cout<<"斜率k:"<<k<<endl;
cout<<"截距b:"<<b<<endl;
cout<<"最佳拟合直线为:\nY="<<exp(b)<<"*Vp^"<<k<<"\n"<<endl;// 最终结果表示为exp(b)*Vp^k
system("PAUSE");
return 0;
}