TheAlgorithms-Python
54 строки · 1.6 Кб
1from collections.abc import Sequence2
3
4def evaluate_poly(poly: Sequence[float], x: float) -> float:5"""Evaluate a polynomial f(x) at specified point x and return the value.6
7Arguments:
8poly -- the coefficients of a polynomial as an iterable in order of
9ascending degree
10x -- the point at which to evaluate the polynomial
11
12>>> evaluate_poly((0.0, 0.0, 5.0, 9.3, 7.0), 10.0)
1379800.0
14"""
15return sum(c * (x**i) for i, c in enumerate(poly))16
17
18def horner(poly: Sequence[float], x: float) -> float:19"""Evaluate a polynomial at specified point using Horner's method.20
21In terms of computational complexity, Horner's method is an efficient method
22of evaluating a polynomial. It avoids the use of expensive exponentiation,
23and instead uses only multiplication and addition to evaluate the polynomial
24in O(n), where n is the degree of the polynomial.
25
26https://en.wikipedia.org/wiki/Horner's_method
27
28Arguments:
29poly -- the coefficients of a polynomial as an iterable in order of
30ascending degree
31x -- the point at which to evaluate the polynomial
32
33>>> horner((0.0, 0.0, 5.0, 9.3, 7.0), 10.0)
3479800.0
35"""
36result = 0.037for coeff in reversed(poly):38result = result * x + coeff39return result40
41
42if __name__ == "__main__":43"""44Example:
45>>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7.0x^4 + 9.3x^3 + 5.0x^2
46>>> x = -13.0
47>>> # f(-13) = 7.0(-13)^4 + 9.3(-13)^3 + 5.0(-13)^2 = 180339.9
48>>> evaluate_poly(poly, x)
49180339.9
50"""
51poly = (0.0, 0.0, 5.0, 9.3, 7.0)52x = 10.053print(evaluate_poly(poly, x))54print(horner(poly, x))55