Mapytex/mapytex/calculus/core/MO/polynomial.py

81 lines
2.3 KiB
Python
Raw Normal View History

2018-11-12 08:41:39 +00:00
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 lafrite <lafrite@Poivre>
#
# Distributed under terms of the MIT license.
from mapytex.calculus.core.tree import Tree
from .mo import MO, MOnumber, MOstr
from .exceptions import MOError
from ..renders import tree2txt, tree2tex
2018-11-13 09:58:32 +00:00
from .monomial import MOMonomial
2018-11-12 08:41:39 +00:00
__all__ = ["MOpolynomial"]
class MOpolynomial(MO):
""" MO polynomial"""
def __init__(self, variable, coefs):
""" Initiate a MOpolynomial
:param variable: variable of the monomial (a MOstr or later a MOSqrt)
:param coefs: dictionnary {deg: coef} or a list [coef0, coef1...]
:example:
>>> MOpolynomial('x', [1, 2, 3])
2018-11-13 09:58:32 +00:00
<MOpolynomial 3x^2 + 2x + 1>
2018-11-12 08:41:39 +00:00
>>> MOpolynomial('x', [1, 0, 3])
2018-11-13 09:58:32 +00:00
<MOpolynomial 3x^2 + 1>
2018-11-12 08:41:39 +00:00
>>> MOpolynomial('x', {0: 1, 1: 2, 2: 3})
2018-11-13 09:58:32 +00:00
<MOpolynomial 3x^2 + 2x + 1>
2018-11-12 08:41:39 +00:00
>>> MOpolynomial('x', {0: 1, 3: 4})
2018-11-13 09:58:32 +00:00
<MOpolynomial 4x^3 + 1>
>>> MOpolynomial('x', {0: 1, 3: 1})
<MOpolynomial x^3 + 1>
2018-11-12 08:41:39 +00:00
"""
_variable = MO.factory(variable)
if not isinstance(_variable, MOstr):
raise MOError("The variable of a monomial should be convertible into MOstr")
self._variable = _variable
if isinstance(coefs, dict):
2018-11-13 09:58:32 +00:00
_coefs = {MO.factory(d): MO.factory(c) for (d, c) in coefs.items()
if c != 0 }
2018-11-12 08:41:39 +00:00
elif isinstance(coefs, list):
2018-11-13 09:58:32 +00:00
_coefs = {MO.factory(d): MO.factory(c) for (d, c) in enumerate(coefs)
if c != 0 }
2018-11-12 08:41:39 +00:00
else:
raise TypeError("Coefs needs to be a dictionnary or a list")
self._coefs = _coefs
monomials = []
2018-11-13 09:58:32 +00:00
for deg, coef in self._coefs.items():
2018-11-12 08:41:39 +00:00
if deg == 0:
monomials.append(coef)
2018-11-13 09:58:32 +00:00
else:
monomials.append(
MOMonomial(coef, self._variable, deg)
)
tree = Tree.from_list("+", monomials[::-1])
MO.__init__(self, tree)
2018-11-12 08:41:39 +00:00
@property
def variable(self):
return self._variable
@property
def degree(self):
return self._power
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del