URAL-1828 Approximation by a Progression (Least Square Method)
Approximation by a Progression
Time Limit:500 MS |
|
Memory Limit:65536KB |
|
64bit IO Format:% I64d & % I64u |
Submit Status
Description
Your are given a sequence of integers
A1 ,...,
An. Find an arithmetic progression
B1 ,...,
BnFor which the value Σ (
Ai?
Bi) 2 is minimal. The elements of the progression can be non-integral.
Input
The first line contains the number
NOf elements in the sequence (2 ≤
N≤ 10 4). In the second line you are given the integers
A1 ,...,
An; Their absolute values do not exceed 10 4.
Output
Output two numbers separated with a space: the first term of the required arithmetic progression and its difference, with an absolute or relative error of at most 10? 6. It is guaranteed that the answer is unique for all input data.
Sample Input
Input |
Output |
40 6 10 15 |
0.400 4.900 |
4-2 -2 -2 -2 |
-2 0 |
The general an = a1 + (n-1) * d of the arithmetic ssion proportional difference sequence, that is, an = (a1-d) + n * d is the form of a linear equation, while (I, mi) is distributed on both sides of the straight line, requiring a straight line k = d, B = a1-d, so think of the least squares, on Y = kX + B, k = (XY) flat -- X flat * Y flat)/(X ^ 2) flat -- (X flat) ^ 2), B = Y flat -- kX flat. Just find the formula.
#include
#include
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];double 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));double b = y / n - k*(x / n);double a1 = b + k;double d = k;cout <