Skip to content

Commit

Permalink
Implemented Horner's scheme for evaluating UnivariatePolynomial
Browse files Browse the repository at this point in the history
  • Loading branch information
CodeMaxx committed Apr 1, 2016
1 parent 28c5f86 commit dc1958c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
18 changes: 11 additions & 7 deletions symengine/polynomial.cpp
Expand Up @@ -468,14 +468,18 @@ Expression UnivariatePolynomial::max_coef() const {
}

Expression UnivariatePolynomial::eval(const Expression &x) const {
//TODO: Use Horner's Scheme
Expression ans = 0;
for (const auto &p : dict_) {
Expression temp;
temp = pow_ex(x, Expression(p.first));
ans += p.second * temp;
int last_deg = dict_.rbegin()->first;
Expression result, x_pow;

for (auto it = dict_.rbegin(); it != dict_.rend(); ++it) {
x_pow = pow_ex(x, last_deg - it->first);
last_deg = it->first;
result = it->second + expand(x_pow * result);
}
return ans;
x_pow = pow_ex(x, last_deg);
result = expand(result * x_pow);

return result;
}

bool UnivariatePolynomial::is_zero() const {
Expand Down
6 changes: 6 additions & 0 deletions symengine/tests/basic/test_polynomial.cpp
Expand Up @@ -245,6 +245,12 @@ TEST_CASE("Evaluation of UnivariatePolynomial", "[UnivariatePolynomial]")
RCP<const UnivariatePolynomial> a = univariate_polynomial(x, 2, {{0, 1}, {1, 2}, {2, symbol("a")}});

REQUIRE(a->eval(2).get_basic()->__str__() == "5 + 4*a");

a = univariate_polynomial(x, 2, {{-1, 5}, {0, 1}, {1, symbol("a")}, {2, 3}});
REQUIRE(a->eval(2).get_basic()->__str__() == "31/2 + 2*a");

a = univariate_polynomial(x, 2, {{-1, symbol("a")}, {0, 1}, {1, 5}, {2, 3}});
REQUIRE(a->eval(3).get_basic()->__str__() == "43 + (1/3)*a");
}

TEST_CASE("Derivative of UnivariatePolynomial", "[UnivariatePolynomial]")
Expand Down

0 comments on commit dc1958c

Please sign in to comment.