(十)C++基础 STL算法

一、目的和要求

1.熟悉STL常用算法的基本使用方法。

二、具体内容

1.利用STL算法实现最小二乘直线拟合。
问题描述
在这里插入图片描述
在这里插入图片描述在这里插入图片描述
图1 战舰长、宽观测数据散点图,基本呈线性关系

在这里插入图片描述
图2 战舰长、宽观测数据拟合直线的结果

算法实现
提示:可以利用vector保存x,y的数据。利用accumulate和inner_product算法可以很快速的计算x,y的均值和内积。

#include "stdafx.h"
#include "iostream"
#include "vector"
#include "numeric"
using namespace std;

//x, y表示观测数据,a,b表示直线参数,error表示拟合误差, error = sum((ax+b - y)^2)  

void least_squre (vector<float>& x, vector<float>& y, float& a, float& b, float& error)

{
    int n = x.size ();
    float c;
    c = accumulate (x.begin (), x.end (), 0.0) / n;
    float d;
    d = accumulate (y.begin (), y.end (), 0.0) / n;
    float e;
    e = inner_product (x.begin (), x.end (), y.begin (), 0.0) / n - c*d;
    float  f;
    f = inner_product (x.begin (), x.end (), x.begin (), 0.0) / n - c*c;
    a = e / f;
    b = d - a*c;

    error = 0;
    for (int i = 0; i < n; i++) 
    {
        error += pow (a*x[i] + b - y[i], 2);
    }

    //to do list  

}

int main ()

{

    //两组测试数据  

    float x1[] = { 6.19f, 2.51f, 7.29f, 7.01f, 5.7f, 2.66f, 3.98f,2.5f, 9.1f, 4.2f };

    float y1[] = { 5.25f, 2.83f, 6.41f, 6.71f, 5.1f, 4.23f, 5.05f, 1.98f, 10.5f, 6.3f };

    float x2[] = { 208.0f, 152.0f, 113.0f, 227.0f, 137.0f, 238.0f, 178.0f, 104.0f, 191.0f, 130.0f };

    float y2[] = { 21.6f, 15.5f, 10.4f, 31.0f, 13.0f, 32.4f, 19.0f, 10.4f, 19.0f,11.8f };

    //将数组转换为vector  
    vector<float> x3 (x1, x1 + sizeof (x1) / sizeof (float));
    vector<float> x4 (x2, x2 + sizeof (x2) / sizeof (float));
    vector<float> y3 (y1, y1 + sizeof (y1) / sizeof (float));
    vector<float> y4 (y2, y2 + sizeof (y2) / sizeof (float));

    //调用拟合函数  
    float a, b, c, d, e1, e2;
    least_squre (x3, y3, a, b, e1);
    least_squre (x4, y4, c, d, e2);

    //输出拟合结果  
    cout << "1. " << e1 << endl;
    cout << "2. " << e2 << endl;

    return 0;
}

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值