﻿ LeastSquaresPolynomialFit – Algosim documentation
Algosim documentation: LeastSquaresPolynomialFit

# LeastSquaresPolynomialFit

Computes the coefficients of the polynomial that best fits a given set of data in the least squares sense.

## Syntax

• `LeastSquaresPolynomialFit(X, Y, n)`

• `X` and `Y` are vectors of the same size

• `n` is a non-negative integer

## Description

If `X` and `Y` are vectors of the same dimension and `n` a non-negative integer, then `LeastSquaresPolynomialFit(X, Y, n)` returns the vector containing the coefficients of the polynomial `p` of degree at most `n` that best fits the given data in the least squares sense. More explicitly, this means that `p` minimises

`∑ (p(X[i]) - Y[i])².`

The coefficients of `p` are given in ascending order in the returned vector: the first component is the constant term, he second component is the linear term, and so on.

## Examples

`X ≔ SequenceVector(100)`
`(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100)`
`Y ≔ X @ (x ↦ 3⋅x^2 − 5⋅x + 2 + RandomReal() − .5)`
`(0.300800696015, 4.35643573129, 14.4663448497, 30.2529292924, 52.012891463, 80.4071306169, 113.896610469, 153.916143032, 200.028036816, 251.676482832, 309.702709734, 373.699384985, 443.988248159, 520.098914632, 601.928580089, 690.431473234, 783.833270203, 884.101421055, 990.100554151, 1102.45085797, 1219.53928946, 1343.7346124, 1474.07007211, 1609.75668351, 1751.56174431, 1900.32426454, 2054.4589332, 2214.17254562, 2380.34161161, 2552.440252, 2729.69146122, 2914.44481914, 3104.48454488, 3300.22973887, 3501.84795911, 3710.44743095, 3924.47223906, 4144.41150258, 4369.82382765, 4601.91495323, 4840.01539681, 5084.4782654, 5333.52872311, 5590.375892, 5852.40767137, 6119.90390882, 6394.11012909, 6674.20804608, 6960.48996103, 7252.40244569, 7550.43571732, 7853.9878112, 8164.08443008, 8479.53562524, 8802.31887256, 9129.55530459, 9464.00763139, 9804.21604584, 10150.2217566, 10502.4671848, 10860.0221056, 11223.9026506, 11594.4202862, 11969.7590416, 12352.3358315, 12739.5354809, 13133.8654004, 13534.189232, 13939.5089039, 14351.5065623, 14770.2249914, 15194.3860353, 15623.8768117, 16060.2137991, 16501.8408748, 16949.5700048, 17403.8496938, 17863.9947507, 18329.5851742, 18801.7733886, 19279.6969458, 19764.4871665, 20253.8504942, 20749.7284969, 21251.6765535, 21759.7131535, 22274.1582578, 22793.8468885, 23319.618528, 23852.4338512, 24390.1195831, 24933.9612534, 25484.3218174, 26039.5714901, 26601.7330737, 27169.7518654, 27744.3740698, 28323.7457076, 28910.2538983, 29502.0294799)`
`LeastSquaresPolynomialFit(X, Y, 2)`
``` ⎛2.08764921226 ⎞
e⎜−4.99864743151⎟
⎝2.99996573585 ⎠
```