Skip to content

Module polynomial.binomial

This module defines different types of binomials and their methods.

View Source
"""This module defines different types of binomials and their methods."""

from polynomial.core import (

    Polynomial,

    Monomial,

    FixedDegreePolynomial,

    FixedTermPolynomial

)

class Binomial(FixedTermPolynomial, valid_term_counts=(0, 1, 2)):

    """Implements single-variable mathematical binomials."""

    def __init__(self, monomial1=None, monomial2=None):

        """Initialize the binomial with 2 monomials.

        The arguments can also be 2-tuples in the form:

            (coefficient, degree)

        """

        if not monomial1:

            monomial1 = Monomial(1, 1)

        if not monomial2:

            monomial2 = Monomial(1, 2)

        Polynomial.__init__(self, [monomial1, monomial2], from_monomials=True)

    def __repr__(self):

        """Return repr(self)."""

        terms = self.terms

        assert len(terms) == 2

        t1, t2 = terms

        return (

            "Binomial(Monomial({0}, {1}), Monomial({2}, {3}))"

            .format(*t1, *t2)

        )

class LinearBinomial(FixedDegreePolynomial, Binomial, valid_degrees=1):

    """Implements linear binomials and their methods."""

    def __init__(self, a=1, b=1):

        """Initialize the binomial as ax + b."""

        if a == 0:

            raise ValueError("object not a linear binomial since a = 0!")

        Polynomial.__init__(self, [a, b])

    @property

    def root(self):

        """Solve for ax + b = 0."""

        return -self.b / self.a

    def __repr__(self):

        """Return repr(self)."""

        return "LinearBinomial({0!r}, {1!r})".format(self.a, self.b)

Classes

Binomial

class Binomial(
    monomial1=None,
    monomial2=None
)

Implements single-variable mathematical binomials.

View Source
class Binomial(FixedTermPolynomial, valid_term_counts=(0, 1, 2)):

    """Implements single-variable mathematical binomials."""

    def __init__(self, monomial1=None, monomial2=None):

        """Initialize the binomial with 2 monomials.

        The arguments can also be 2-tuples in the form:

            (coefficient, degree)

        """

        if not monomial1:

            monomial1 = Monomial(1, 1)

        if not monomial2:

            monomial2 = Monomial(1, 2)

        Polynomial.__init__(self, [monomial1, monomial2], from_monomials=True)

    def __repr__(self):

        """Return repr(self)."""

        terms = self.terms

        assert len(terms) == 2

        t1, t2 = terms

        return (

            "Binomial(Monomial({0}, {1}), Monomial({2}, {3}))"

            .format(*t1, *t2)

        )

Ancestors (in MRO)

  • polynomial.core.FixedTermPolynomial
  • polynomial.core.Polynomial

Descendants

  • polynomial.binomial.LinearBinomial

Class variables

valid_term_counts

Static methods

zero_instance
def zero_instance(

)

Return the Polynomial which is 0.

View Source
    @classmethod

    def zero_instance(cls):

        """Return the Polynomial which is 0."""

        return Polynomial()

Instance variables

degree

Return the degree of the polynomial.

derivative

Return a polynomial object which is the derivative of self.

monomials

Return a list with all terms in the form of monomials.

List is sorted from the highest degree term to the lowest.

terms

Get the terms of self as a list of tuples in coeff, deg form.

Terms are returned from largest degree to smallest degree, excluding any terms with a zero coefficient.

Methods

calculate
def calculate(
    self,
    x
)

Calculate the value of the polynomial at a given point.

View Source
    def calculate(self, x):

        """Calculate the value of the polynomial at a given point."""

        if self.degree < 0:

            return 0

        return sum(ak * (x ** k) for ak, k in self.terms)
nth_derivative
def nth_derivative(
    self,
    n=1
)

Return the polynomial object which is the nth derivative of self.

View Source
    def nth_derivative(self, n=1):

        """Return the polynomial object which is the nth derivative of self."""

        if not isinstance(n, int) or n < 0:

            raise ValueError(

                "n must be a non-negative integer (got {0})".format(n)

            )

        if not self or n > self.degree:

            # Short circuit since the result would be zero.

            return self.zero_instance()

        if n == 0:

            return deepcopy(self)

        if n == 1:

            factors = range(1, self.degree + 1)

        else:

            d = self.degree - n + 1

            factorial_term = n + 1

            factors = [1] * d

            # Calculate n! for base term.

            for i in range(1, factorial_term):

                factors[0] *= i

            for i in range(1, d):

                # The last number is n * (n-1) * (n-2) * ... * i

                # The next number is (n+1) * n * (n-1) * ... * i + 1

                # To get the next number, we multiply the last number by

                # n + 1 and divide by i.

                factors[i] = (factors[i - 1] // i) * factorial_term

                factorial_term += 1

        return Polynomial(

            [c * x for c, x

             in zip(self, reversed(factors))]

        )
terms_are_valid
def terms_are_valid(
    self,
    terms
)
View Source
        def terms_are_valid(self, terms):

            return (

                _terms_are_valid(self, terms)

                and orig_terms_are_valid(self, terms)

            )
try_set_self
def try_set_self(
    self,
    terms
)

Try applying terms to self if possible.

If not possible, returns a Polynomial with the terms.

View Source
    def try_set_self(self, terms):

        """Try applying terms to self if possible.

        If not possible, returns a Polynomial with the terms.

        """

        if self.terms_are_valid(terms):

            self.terms = terms

            return self

        return Polynomial(terms, from_monomials=True)

LinearBinomial

class LinearBinomial(
    a=1,
    b=1
)

Implements linear binomials and their methods.

View Source
class LinearBinomial(FixedDegreePolynomial, Binomial, valid_degrees=1):

    """Implements linear binomials and their methods."""

    def __init__(self, a=1, b=1):

        """Initialize the binomial as ax + b."""

        if a == 0:

            raise ValueError("object not a linear binomial since a = 0!")

        Polynomial.__init__(self, [a, b])

    @property

    def root(self):

        """Solve for ax + b = 0."""

        return -self.b / self.a

    def __repr__(self):

        """Return repr(self)."""

        return "LinearBinomial({0!r}, {1!r})".format(self.a, self.b)

Ancestors (in MRO)

  • polynomial.core.FixedDegreePolynomial
  • polynomial.binomial.Binomial
  • polynomial.core.FixedTermPolynomial
  • polynomial.core.Polynomial

Class variables

valid_degrees
valid_term_counts

Static methods

zero_instance
def zero_instance(

)

Return the Polynomial which is 0.

View Source
    @classmethod

    def zero_instance(cls):

        """Return the Polynomial which is 0."""

        return Polynomial()

Instance variables

degree

Return the degree of the polynomial.

derivative

Return a polynomial object which is the derivative of self.

monomials

Return a list with all terms in the form of monomials.

List is sorted from the highest degree term to the lowest.

root

Solve for ax + b = 0.

terms

Get the terms of self as a list of tuples in coeff, deg form.

Terms are returned from largest degree to smallest degree, excluding any terms with a zero coefficient.

Methods

calculate
def calculate(
    self,
    x
)

Calculate the value of the polynomial at a given point.

View Source
    def calculate(self, x):

        """Calculate the value of the polynomial at a given point."""

        if self.degree < 0:

            return 0

        return sum(ak * (x ** k) for ak, k in self.terms)
nth_derivative
def nth_derivative(
    self,
    n=1
)

Return the polynomial object which is the nth derivative of self.

View Source
    def nth_derivative(self, n=1):

        """Return the polynomial object which is the nth derivative of self."""

        if not isinstance(n, int) or n < 0:

            raise ValueError(

                "n must be a non-negative integer (got {0})".format(n)

            )

        if not self or n > self.degree:

            # Short circuit since the result would be zero.

            return self.zero_instance()

        if n == 0:

            return deepcopy(self)

        if n == 1:

            factors = range(1, self.degree + 1)

        else:

            d = self.degree - n + 1

            factorial_term = n + 1

            factors = [1] * d

            # Calculate n! for base term.

            for i in range(1, factorial_term):

                factors[0] *= i

            for i in range(1, d):

                # The last number is n * (n-1) * (n-2) * ... * i

                # The next number is (n+1) * n * (n-1) * ... * i + 1

                # To get the next number, we multiply the last number by

                # n + 1 and divide by i.

                factors[i] = (factors[i - 1] // i) * factorial_term

                factorial_term += 1

        return Polynomial(

            [c * x for c, x

             in zip(self, reversed(factors))]

        )
terms_are_valid
def terms_are_valid(
    self,
    terms
)
View Source
        def terms_are_valid(self, terms):

            return (

                _terms_are_valid(self, terms)

                and orig_terms_are_valid(self, terms)

            )
try_set_self
def try_set_self(
    self,
    terms
)

Try applying terms to self if possible.

If not possible, returns a Polynomial with the terms.

View Source
    def try_set_self(self, terms):

        """Try applying terms to self if possible.

        If not possible, returns a Polynomial with the terms.

        """

        if self.terms_are_valid(terms):

            self.terms = terms

            return self

        return Polynomial(terms, from_monomials=True)