2022-07-11 08:19:52 +00:00
|
|
|
from collections.abc import Sequence
|
2019-10-17 14:50:51 +00:00
|
|
|
|
|
|
|
|
|
|
|
def evaluate_poly(poly: Sequence[float], x: float) -> float:
|
|
|
|
"""Evaluate a polynomial f(x) at specified point x and return the value.
|
2019-10-01 06:58:00 +00:00
|
|
|
|
2019-10-17 14:50:51 +00:00
|
|
|
Arguments:
|
2021-03-20 05:12:17 +00:00
|
|
|
poly -- the coefficients of a polynomial as an iterable in order of
|
2019-10-17 14:50:51 +00:00
|
|
|
ascending degree
|
|
|
|
x -- the point at which to evaluate the polynomial
|
|
|
|
|
|
|
|
>>> evaluate_poly((0.0, 0.0, 5.0, 9.3, 7.0), 10.0)
|
|
|
|
79800.0
|
|
|
|
"""
|
2022-01-30 19:29:54 +00:00
|
|
|
return sum(c * (x**i) for i, c in enumerate(poly))
|
2019-10-01 06:58:00 +00:00
|
|
|
|
|
|
|
|
2019-10-17 14:50:51 +00:00
|
|
|
def horner(poly: Sequence[float], x: float) -> float:
|
|
|
|
"""Evaluate a polynomial at specified point using Horner's method.
|
|
|
|
|
|
|
|
In terms of computational complexity, Horner's method is an efficient method
|
|
|
|
of evaluating a polynomial. It avoids the use of expensive exponentiation,
|
|
|
|
and instead uses only multiplication and addition to evaluate the polynomial
|
|
|
|
in O(n), where n is the degree of the polynomial.
|
|
|
|
|
|
|
|
https://en.wikipedia.org/wiki/Horner's_method
|
|
|
|
|
|
|
|
Arguments:
|
2021-03-20 05:12:17 +00:00
|
|
|
poly -- the coefficients of a polynomial as an iterable in order of
|
2019-10-17 14:50:51 +00:00
|
|
|
ascending degree
|
|
|
|
x -- the point at which to evaluate the polynomial
|
|
|
|
|
|
|
|
>>> horner((0.0, 0.0, 5.0, 9.3, 7.0), 10.0)
|
|
|
|
79800.0
|
|
|
|
"""
|
|
|
|
result = 0.0
|
|
|
|
for coeff in reversed(poly):
|
|
|
|
result = result * x + coeff
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
2019-10-01 06:58:00 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
"""
|
2019-10-17 14:50:51 +00:00
|
|
|
Example:
|
|
|
|
>>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7.0x^4 + 9.3x^3 + 5.0x^2
|
|
|
|
>>> x = -13.0
|
2020-06-16 08:09:19 +00:00
|
|
|
>>> # f(-13) = 7.0(-13)^4 + 9.3(-13)^3 + 5.0(-13)^2 = 180339.9
|
|
|
|
>>> print(evaluate_poly(poly, x))
|
2019-10-17 14:50:51 +00:00
|
|
|
180339.9
|
2019-10-01 06:58:00 +00:00
|
|
|
"""
|
|
|
|
poly = (0.0, 0.0, 5.0, 9.3, 7.0)
|
2019-10-17 14:50:51 +00:00
|
|
|
x = 10.0
|
2019-10-01 06:58:00 +00:00
|
|
|
print(evaluate_poly(poly, x))
|
2019-10-17 14:50:51 +00:00
|
|
|
print(horner(poly, x))
|