当前位置:网站首页>线性回归——以一道等差数列的题为例
线性回归——以一道等差数列的题为例
2022-07-26 17:09:00 【Shanhj】
对于一组 xi 和 yi 计算线性回归方程的公式如下:
题目大意:给定一个数列,将其变成等差数列,修改的代价是
求最小代价
直接套用上面的线性回归方程公式即可。
#include <bits/stdc++.h>
#define inf 0x3f3f3f3f
const long long N = 3e5 + 5;
using namespace std;
namespace GTI //快读模板
{
char gc(void)
{
const long long S = 1 << 16;
static char buf[S], *s = buf, *t = buf;
if (s == t) t = buf + fread(s = buf, 1, S, stdin);
if (s == t) return EOF;
return *s++;
}
long long gti(void)
{
long long a = 0, b = 1, c = gc();
for (; !isdigit(c); c = gc())
b ^= (c == '-');
for (; isdigit(c); c = gc())
a = a * 10 + c - '0';
return b ? a : -a;
}
}
using GTI::gti;
long long num[N];
signed main()
{
long long T;
T = gti();
while (T--)
{
long long n = gti();
long long sxy = 0, sx = 0, sy = 0, sx2 = 0;
long double b, a, ans = 0;
for (long long i = 1; i <= n; i++)
{
num[i] = gti();
sxy += i * num[i];
sx += i;
sy += num[i];
sx2 += i * i;
}
b = ((long double)n * sxy - (long double)sx * sy) / ((long double)n * sx2 - (long double)sx * sx);
a = (long double)sy / n - b * sx / n;
long double ai = a;
for (long long i = 1; i <= n; i++)
{
ai += b;
ans += (num[i] - ai) * (num[i] - ai);
}
printf("%.10lf\n", ans);
}
return 0;
}
边栏推荐
猜你喜欢

Spark data format unsafe row

Open source kaggle cat and dog data set -- used in classic CNN classification practice

Three ways of de duplication in SQL

How to assemble a registry?

Come on developer! Not only for the 200000 bonus, try the best "building blocks" for a brainstorming
![[metauniverse OMI theory] analyze Web3 risk challenges and build Web3 ecological security](/img/d1/4a424d810f7a6aaccae80b4fe232c0.png)
[metauniverse OMI theory] analyze Web3 risk challenges and build Web3 ecological security
![[Oumi reading club] talk about the creator economy in the meta universe: infinite dimension](/img/60/17cb0295f81dc580cc3ff8543ec253.png)
[Oumi reading club] talk about the creator economy in the meta universe: infinite dimension

带你熟悉云网络的“电话簿”:DNS
![[day3] reconstruction of roads](/img/52/cc8b81bccbf4aa02ec82fedfb49d19.png)
[day3] reconstruction of roads

大咖访谈 | 开源对安全是双刃剑——《大教堂与集市》中文译本作者卫剑钒
随机推荐
Interview with celebrities | open source is a double-edged sword for security -- Wei Jianfan, author of the Chinese translation of cathedral and market
2、 Topic communication principle, code implementation
Win10 连接无线不能输入密码字符,一输入就卡死
[training Day2] torchbearer
6-19 vulnerability exploitation -nsf to obtain the target password file
跨站脚本攻击(XSS)
SQL中去去重的三种方式
DTS搭载全新自研内核,突破两地三中心架构的关键技术|腾讯云数据库
AI遮天传 ML-无监督学习
重磅!《2022中国开源发展蓝皮书》正式发布
We were tossed all night by a Kong performance bug
Basic select statement
Coscon'22 city / school / institution producer solicitation order
Kudu design tablet
VIM多行操作
Diagram of seven connection modes of MySQL
JS recursive Fibonacci sequence deep cloning
hosts该文件已设置为只读的解决方法
4、 Service communication principle, code implementation
Cross site scripting attack (XSS)