Python Forum
Generating a polynomial equation
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Generating a polynomial equation
#2
Definitely, you need to create a class Polynom. Instances of that class will be polynomials. Further, you can override arithmetic operations to be able to add two polynomials, multiply polynomials each other etc.
As a starting point, I just wrote some code defining Polynom class.

import sys
import types
from numbers import Number
from abc import ABCMeta, abstractmethod
from collections.abc import Sequence
from itertools import zip_longest


class PolynomBase(metaclass=ABCMeta):
    eps = sys.float_info.epsilon
    
    def __init__(self, coefficients):
        """Initialize a polynom"""

        if isinstance(coefficients, Sequence):
            self.coefficients = tuple(coefficients)
            if not all(map(lambda x: isinstance(x, Number), self.coefficients)):
                raise Exception("Array of coefficients should contain numbers only.")
            if len(self.coefficients) == 0:
                raise Exception("Length of the array of coefficients is zero.")
            if all(map(lambda x: abs(x) < self.eps , self.coefficients)):
                raise Exception("At least one coefficient of the polynom should be greater than eps = {}".format(eps))
        else:
            raise Exception("Array of coeffcients should be of sequence type")
    
    def __repr__(self):
        """Official representation of the polynomial object"""
        return self.__str__()

    def __str__(self):
        """Polynom pretty printing"""
        return ' + '.join("{}x^{}".format(c, i) for i, c in enumerate(self.coefficients))
    
    @abstractmethod
    def calculate(self, x):
        """Returns value of P(x)"""

    @abstractmethod
    def __add__(self, other):
        """Polynom addition"""

#     @abstractmethod
#     def __sub__(self, other):
#         """Polynom substraction"""

#     @abstractmethod
#     def __mul__(self, other):
#         """Polynom multiplication"""

    def __len__(self):
        return self.degree + 1

    @property
    @abstractmethod
    def degree(self):
        """Returns degree of a polynom"""


class Polynom(PolynomBase):
    
    def __init__(self, coefficients):
        super().__init__(coefficients)
    
    def __add__(self, other):
        if isinstance(other, PolynomBase):
            coefficients = []
            for a, b in zip_longest(self.coefficients, other.coefficients, fillvalue=0.0):
                coefficients.append(a + b)
            return Polynom(coefficients)
        elif isinstance(other, Number):
            coefficients = list(self.coefficients)
            coefficients[0] += other
            return Polynom(coefficients)
        raise Exception("Could not add an object of {} to an object of {}".format(type(self), type(other)))

    def __radd__(self, other):
        return self.__add__(other)

    def calculate(self, x):
        res = 0.0
        for p, j in enumerate(self.coefficients):
            res += j * x ** p
        return res
        
    @property
    def degree(self):
        return len(self.coefficients) - 1

    # you need to define additional methods here.
p = Polynom((1,2,3))
print(p)
Output:
1*x^0 + 2*x^1 + 3*x^2
p + 3
Output:
4*x^0 + 2*x^1 + 3*x^2
Reply


Messages In This Thread
Generating a polynomial equation - by BinaryStar - Mar-17-2019, 12:23 AM
RE: Generating a polynomial equation - by scidam - Mar-17-2019, 07:57 AM
RE: Generating a polynomial equation - by scidam - Mar-18-2019, 12:53 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020