URAL-1828 approximation by a progression (least squares)

Source: Internet
Author: User

Approximation by a progression
Time Limit: 500MS Memory Limit: 65536KB 64bit IO Format: %i64d &%i64u

Submit Status

Description

Your is given a sequence of integers  a1,...,  an. Find an arithmetic progression  b1,...,  Bn for which the Value∑ (  AI ?  Bi) 2 is minimal. The elements of the progression can be non-integral.

Input

The first line contains the number  N of elements in the sequence (2≤  N ≤10 4). The second line given the integers  a1,...,  an; Their absolute values do not exceed 10 4.

Output

Output numbers separated with a space:the first term of the required arithmetic progression and its difference, with An absolute or relative error of in most 10 ? 6. It is guaranteed, the answer is unique for all input data.

sample Input

input output
40 6 
0.400 4.900 
4-2 -2-2-2 
-2 0 


Arithmetic progression arithmetic progression of the general formula an=a1+ (n-1) *d, that is an= (a1-d) +n*d is the form of linear equations, and (I,mi) is distributed on both sides of the line, requiring a straight line of k=d,b=a1-d, so think of the least squares, For Y=kx+b, there are k= ((XY) flat--x flat *y Flat)/((x^2) flat-(X flat) ^2), B=y flat--kx flat. It's OK to do it by the formula.

#include <iostream> #include <iomanip>using namespace std;const int maxn = 10005;double A[maxn];int Main () { int N;while (CIN >> N) {for (int i = 1; I <= n; i++) cin >> A[i];d ouble xy=0, x=0, y=0, x2=0;for (int i = 1; I <= N; i++) {xy = xy + a[i] * i;x = x + i;y = y + a[i];x2 = x2 + i*i;}  Double k = (xy/n-(x/n) * (y/n))/(x2/n  -(x/n) * (x/n));d ouble B = y/n-k* (x/n);d ouble a1 = b + k;double d = k;cout <<fixed<<setprecision (6) << A1 << "" <<fixed<<setprecision (6) <<k << Endl;}}


URAL-1828 approximation by a progression (least squares)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.