Polynomial evaluation: what changed
Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.
Title: Polynomial evaluation
| Old | New | Line | |
|---|---|---|---|
| 1 | + | # Introduction | |
| 2 | + | ||
| 3 | + | It is often useful to evaluate a polynomial at a given point. The method shown below allows to calculate it by using only multiplication and addition, without any power. | |
| 4 | + | ||
| 5 | + | # Horner's method | |
| 6 | + | ||
| 7 | + | Only 1-degree polynomial are evaluated, e.g. 3.x^2 + 2.x + 1, can be written, by means of an astute factorization, ((3.x +2).x + 1). | |
| 8 | + | ||
| 9 | + | ``` pascal | |
| 10 | + | program PolyTest; | |
| 11 | + | ||
| 12 | + | type | |
| 13 | + | // coef's rank = it's degree | |
| 14 | + | TDegres = 0..10; | |
| 15 | + | TPolynome = record | |
| 16 | + | Deg: TDegres; | |
| 17 | + | Coefs: array[TDegres] of Double; | |
| 18 | + | end; | |
| 19 | + | ||
| 20 | + | function PolyEval(const aPoly: TPolynome; X: Double): Double; | |
| 21 | + | var | |
| 22 | + | i: TDegres; | |
| 23 | + | begin | |
| 24 | + | with aPoly do | |
| 25 | + | begin | |
| 26 | + | Result := 0; | |
| 27 | + | for i := Deg downto Low(Coefs) do | |
| 28 | + | Result := Result * X + Coefs[i]; | |
| 29 | + | end; | |
| 30 | + | End; | |
| 31 | + | ||
| 32 | + | (* Exemples *) | |
| 33 | + | var | |
| 34 | + | P: TPolynome; | |
| 35 | + | begin | |
| 36 | + | P.Deg := 2; | |
| 37 | + | P.Coefs[2] := 3; | |
| 38 | + | P.Coefs[1] := 2; | |
| 39 | + | P.Coefs[0] := 1; | |
| 40 | + | WriteLn('P(',7,') = ', PolyEval(7):10:2); | |
| 41 | + | ||
| 42 | + | P.Deg := 0; | |
| 43 | + | P.Coefs[2] := 0; | |
| 44 | + | P.Coefs[1] := 0; | |
| 45 | + | P.Coefs[0] := 1; | |
| 46 | + | WriteLn('P(',7,') = ', PolyEval(7):10:2); | |
| 47 | + | End | |
| 48 | + | ``` | |
| 49 | + | ||
| 50 | + | # See also | |
| 51 | + | ||
| 52 | + | \[<https://en.wikipedia.org/wiki/Horner%27s_method>\| Horner's method (wiki)\] | |
| 53 | + | ||
| 54 | + | --- | |
| 55 | + | *From the Free Pascal wiki, page "Polynomial evaluation", as it stood on 2020-02-23 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).* |
