Skip to content

added horner's method #1360

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 17, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 44 additions & 16 deletions maths/polynomial_evaluation.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,53 @@
def evaluate_poly(poly, x):
"""
Objective: Computes the polynomial function for a given value x.
Returns that value.
Input Prams:
poly: tuple of numbers - value of cofficients
x: value for x in f(x)
Return: value of f(x)

>>> evaluate_poly((0.0, 0.0, 5.0, 9.3, 7.0), 10)
79800.0
"""
from typing import Sequence


def evaluate_poly(poly: Sequence[float], x: float) -> float:
"""Evaluate a polynomial f(x) at specified point x and return the value.

Arguments:
poly -- the coeffiecients of a polynomial as an iterable in order of
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
"""
return sum(c * (x ** i) for i, c in enumerate(poly))


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:
poly -- the coeffiecients of a polynomial as an iterable in order of
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


if __name__ == "__main__":
"""
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
print (evaluate_poly(poly, x)) # f(-13) = 7.0(-13)^4 + 9.3(-13)^3 + 5.0(-13)^2 = 180339.9
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
>>> print(evaluate_poly(poly, x)) # f(-13) = 7.0(-13)^4 + 9.3(-13)^3 + 5.0(-13)^2 = 180339.9
180339.9
"""
poly = (0.0, 0.0, 5.0, 9.3, 7.0)
x = 10
x = 10.0
print(evaluate_poly(poly, x))
print(horner(poly, x))