summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoss Barnowski <rossbar@berkeley.edu>2020-02-27 16:30:54 -0800
committerRoss Barnowski <rossbar@berkeley.edu>2020-05-07 10:26:32 -0700
commit9c83b13ce1b08aed8181d284566d002086393a89 (patch)
treee0d8e8316290306ab381e6997399630f0ff1ef01
parent965b41d418e6100c1afae0b6f818a7ef152bc25d (diff)
downloadnumpy-9c83b13ce1b08aed8181d284566d002086393a89.tar.gz
ENH: Improved __str__, __format__ for polynomials
Changes the printing style of instances of the convenience classes in the polynomial package to a more "human-readable" format. __str__ has been modified and __format__ added to ABCPolyBase, modifying the string representation of polynomial instances, e.g. when printed. __repr__ and the _repr_latex method (which is used in the Jupyter environment are unchanged. Two print formats have been added: 'unicode' and 'ascii'. 'unicode' is the default mode on *nix systems, and uses unicode values for numeric subscripts and superscripts in the polynomial expression. The 'ascii' format is the default on Windows (due to font considerations) and uses Python-style syntax to represent powers, e.g. x**2. The default printing style can be controlled at the package-level with the set_default_printstyle function. The ABCPolyBase.__str__ has also been made to respect the linewidth printoption. Other parameters from the printoptions dictionary are not used. Co-Authored-By: Warren Weckesser <warren.weckesser@gmail.com> Co-authored-by: Eric Wieser <wieser.eric@gmail.com>
-rw-r--r--doc/release/upcoming_changes/15666.improvement.rst8
-rw-r--r--numpy/polynomial/__init__.py50
-rw-r--r--numpy/polynomial/_polybase.py110
-rw-r--r--numpy/polynomial/polynomial.py8
-rw-r--r--numpy/polynomial/tests/test_printing.py271
5 files changed, 424 insertions, 23 deletions
diff --git a/doc/release/upcoming_changes/15666.improvement.rst b/doc/release/upcoming_changes/15666.improvement.rst
new file mode 100644
index 000000000..c42d70952
--- /dev/null
+++ b/doc/release/upcoming_changes/15666.improvement.rst
@@ -0,0 +1,8 @@
+Improved string representation for polynomials (__str__)
+--------------------------------------------------------
+
+The string representation (``__str__``) of all six polynomial types in
+`numpy.polynomial` has been updated to give the polynomial as a mathematical
+expression instead of an array of coefficients. Two package-wide formats for
+the polynomial expressions are available - one using Unicode characters for
+superscripts and subscripts, and another using only ASCII characters.
diff --git a/numpy/polynomial/__init__.py b/numpy/polynomial/__init__.py
index 4ff2df57e..43b2caba3 100644
--- a/numpy/polynomial/__init__.py
+++ b/numpy/polynomial/__init__.py
@@ -20,6 +20,56 @@ from .hermite import Hermite
from .hermite_e import HermiteE
from .laguerre import Laguerre
+
+def set_default_printstyle(style):
+ """
+ Set the default format for the string representation of polynomials.
+
+ Values for ``style`` must be valid inputs to ``__format__``, i.e. 'ascii'
+ or 'unicode'.
+
+ Parameters
+ ----------
+ style : str
+ Format string for default printing style. Must be either 'ascii' or
+ 'unicode'.
+
+ Notes
+ -----
+ The default format depends on the platform: 'unicode' is used on
+ Unix-based systems and 'ascii' on Windows. This determination is based on
+ default font support for the unicode superscript and subscript ranges.
+
+ Examples
+ --------
+ >>> p = np.polynomial.Polynomial([1, 2, 3])
+ >>> c = np.polynomial.Chebyshev([1, 2, 3])
+ >>> np.polynomial.set_default_printstyle('unicode')
+ >>> print(p)
+ 1.0 + 2.0·x¹ + 3.0·x²
+ >>> print(c)
+ 1.0 + 2.0·T₁(x) + 3.0·T₂(x)
+ >>> np.polynomial.set_default_printstyle('ascii')
+ >>> print(p)
+ 1.0 + 2.0 x**1 + 3.0 x**2
+ >>> print(c)
+ 1.0 + 2.0 T_1(x) + 3.0 T_2(x)
+ >>> # Formatting supercedes all class/package-level defaults
+ >>> print(f"{p:unicode}")
+ 1.0 + 2.0·x¹ + 3.0·x²
+ """
+ if style not in ('unicode', 'ascii'):
+ raise ValueError(
+ f"Unsupported format string '{style}'. Valid options are 'ascii' "
+ f"and 'unicode'"
+ )
+ _use_unicode = True
+ if style == 'ascii':
+ _use_unicode = False
+ from ._polybase import ABCPolyBase
+ ABCPolyBase._use_unicode = _use_unicode
+
+
from numpy._pytesttester import PytestTester
test = PytestTester(__name__)
del PytestTester
diff --git a/numpy/polynomial/_polybase.py b/numpy/polynomial/_polybase.py
index 53efbb90f..253aa74e8 100644
--- a/numpy/polynomial/_polybase.py
+++ b/numpy/polynomial/_polybase.py
@@ -6,6 +6,7 @@ for the various polynomial classes. It operates as a mixin, but uses the
abc module from the stdlib, hence it is only available for Python >= 2.6.
"""
+import os
import abc
import numbers
@@ -67,6 +68,37 @@ class ABCPolyBase(abc.ABC):
# Limit runaway size. T_n^m has degree n*m
maxpower = 100
+ # Unicode character mappings for improved __str__
+ _superscript_mapping = str.maketrans({
+ "0": "⁰",
+ "1": "¹",
+ "2": "²",
+ "3": "³",
+ "4": "⁴",
+ "5": "⁵",
+ "6": "⁶",
+ "7": "⁷",
+ "8": "⁸",
+ "9": "⁹"
+ })
+ _subscript_mapping = str.maketrans({
+ "0": "₀",
+ "1": "₁",
+ "2": "₂",
+ "3": "₃",
+ "4": "₄",
+ "5": "₅",
+ "6": "₆",
+ "7": "₇",
+ "8": "₈",
+ "9": "₉"
+ })
+ # Some fonts don't support full unicode character ranges necessary for
+ # the full set of superscripts and subscripts, including common/default
+ # fonts in Windows shells/terminals. Therefore, default to ascii-only
+ # printing on windows.
+ _use_unicode = not os.name == 'nt'
+
@property
@abc.abstractmethod
def domain(self):
@@ -283,10 +315,82 @@ class ABCPolyBase(abc.ABC):
name = self.__class__.__name__
return f"{name}({coef}, domain={domain}, window={window})"
+ def __format__(self, fmt_str):
+ if fmt_str == '':
+ return self.__str__()
+ if fmt_str not in ('ascii', 'unicode'):
+ raise ValueError(
+ f"Unsupported format string '{fmt_str}' passed to "
+ f"{self.__class__}.__format__. Valid options are "
+ f"'ascii' and 'unicode'"
+ )
+ if fmt_str == 'ascii':
+ return self._generate_string(self._str_term_ascii)
+ return self._generate_string(self._str_term_unicode)
+
def __str__(self):
- coef = str(self.coef)
- name = self.nickname
- return f"{name}({coef})"
+ if self._use_unicode:
+ return self._generate_string(self._str_term_unicode)
+ return self._generate_string(self._str_term_ascii)
+
+ def _generate_string(self, term_method):
+ """
+ Generate the full string representation of the polynomial, using
+ ``term_method`` to generate each polynomial term.
+ """
+ # Get configuration for line breaks
+ linewidth = np.get_printoptions().get('linewidth', 75)
+ if linewidth < 1:
+ linewidth = 1
+ out = f"{self.coef[0]}"
+ for i, coef in enumerate(self.coef[1:]):
+ out += " "
+ power = str(i + 1)
+ # Polynomial coefficient
+ if coef >= 0:
+ next_term = f"+ {coef}"
+ else:
+ next_term = f"- {-coef}"
+ # Polynomial term
+ next_term += term_method(power, "x")
+ # Length of the current line with next term added
+ line_len = len(out.split('\n')[-1]) + len(next_term)
+ # If not the last term in the polynomial, it will be two
+ # characters longer due to the +/- with the next term
+ if i < len(self.coef[1:]) - 1:
+ line_len += 2
+ # Handle linebreaking
+ if line_len >= linewidth:
+ next_term = next_term.replace(" ", "\n", 1)
+ out += next_term
+ return out
+
+ @classmethod
+ def _str_term_unicode(cls, i, arg_str):
+ """
+ String representation of single polynomial term using unicode
+ characters for superscripts and subscripts.
+ """
+ if cls.basis_name is None:
+ raise NotImplementedError(
+ "Subclasses must define either a basis_name, or override "
+ "_str_term_unicode(cls, i, arg_str)"
+ )
+ return (f"·{cls.basis_name}{i.translate(cls._subscript_mapping)}"
+ f"({arg_str})")
+
+ @classmethod
+ def _str_term_ascii(cls, i, arg_str):
+ """
+ String representation of a single polynomial term using ** and _ to
+ represent superscripts and subscripts, respectively.
+ """
+ if cls.basis_name is None:
+ raise NotImplementedError(
+ "Subclasses must define either a basis_name, or override "
+ "_str_term_ascii(cls, i, arg_str)"
+ )
+ return f" {cls.basis_name}_{i}({arg_str})"
@classmethod
def _repr_latex_term(cls, i, arg_str, needs_parens):
diff --git a/numpy/polynomial/polynomial.py b/numpy/polynomial/polynomial.py
index 2fb032db3..97f1e7dc0 100644
--- a/numpy/polynomial/polynomial.py
+++ b/numpy/polynomial/polynomial.py
@@ -1495,6 +1495,14 @@ class Polynomial(ABCPolyBase):
window = np.array(polydomain)
basis_name = None
+ @classmethod
+ def _str_term_unicode(cls, i, arg_str):
+ return f"·{arg_str}{i.translate(cls._superscript_mapping)}"
+
+ @staticmethod
+ def _str_term_ascii(i, arg_str):
+ return f" {arg_str}**{i}"
+
@staticmethod
def _repr_latex_term(i, arg_str, needs_parens):
if needs_parens:
diff --git a/numpy/polynomial/tests/test_printing.py b/numpy/polynomial/tests/test_printing.py
index 049d3af2f..acccb23f5 100644
--- a/numpy/polynomial/tests/test_printing.py
+++ b/numpy/polynomial/tests/test_printing.py
@@ -1,38 +1,269 @@
+import pytest
+from numpy.core import arange, printoptions
import numpy.polynomial as poly
-from numpy.testing import assert_equal
+from numpy.testing import assert_equal, assert_
-class TestStr:
- def test_polynomial_str(self):
- res = str(poly.Polynomial([0, 1]))
- tgt = 'poly([0. 1.])'
+class TestStrUnicodeSuperSubscripts:
+
+ @pytest.fixture(scope='class', autouse=True)
+ def use_unicode(self):
+ poly.set_default_printstyle('unicode')
+
+ @pytest.mark.parametrize(('inp', 'tgt'), (
+ ([1, 2, 3], "1.0 + 2.0·x¹ + 3.0·x²"),
+ ([-1, 0, 3, -1], "-1.0 + 0.0·x¹ + 3.0·x² - 1.0·x³"),
+ (arange(12), ("0.0 + 1.0·x¹ + 2.0·x² + 3.0·x³ + 4.0·x⁴ + 5.0·x⁵ + "
+ "6.0·x⁶ + 7.0·x⁷ +\n8.0·x⁸ + 9.0·x⁹ + 10.0·x¹⁰ + "
+ "11.0·x¹¹")),
+ ))
+ def test_polynomial_str(self, inp, tgt):
+ res = str(poly.Polynomial(inp))
assert_equal(res, tgt)
- def test_chebyshev_str(self):
- res = str(poly.Chebyshev([0, 1]))
- tgt = 'cheb([0. 1.])'
+ @pytest.mark.parametrize(('inp', 'tgt'), (
+ ([1, 2, 3], "1.0 + 2.0·T₁(x) + 3.0·T₂(x)"),
+ ([-1, 0, 3, -1], "-1.0 + 0.0·T₁(x) + 3.0·T₂(x) - 1.0·T₃(x)"),
+ (arange(12), ("0.0 + 1.0·T₁(x) + 2.0·T₂(x) + 3.0·T₃(x) + 4.0·T₄(x) + "
+ "5.0·T₅(x) +\n6.0·T₆(x) + 7.0·T₇(x) + 8.0·T₈(x) + "
+ "9.0·T₉(x) + 10.0·T₁₀(x) + 11.0·T₁₁(x)")),
+ ))
+ def test_chebyshev_str(self, inp, tgt):
+ res = str(poly.Chebyshev(inp))
+ assert_equal(res, tgt)
+
+ @pytest.mark.parametrize(('inp', 'tgt'), (
+ ([1, 2, 3], "1.0 + 2.0·P₁(x) + 3.0·P₂(x)"),
+ ([-1, 0, 3, -1], "-1.0 + 0.0·P₁(x) + 3.0·P₂(x) - 1.0·P₃(x)"),
+ (arange(12), ("0.0 + 1.0·P₁(x) + 2.0·P₂(x) + 3.0·P₃(x) + 4.0·P₄(x) + "
+ "5.0·P₅(x) +\n6.0·P₆(x) + 7.0·P₇(x) + 8.0·P₈(x) + "
+ "9.0·P₉(x) + 10.0·P₁₀(x) + 11.0·P₁₁(x)")),
+ ))
+ def test_legendre_str(self, inp, tgt):
+ res = str(poly.Legendre(inp))
+ assert_equal(res, tgt)
+
+ @pytest.mark.parametrize(('inp', 'tgt'), (
+ ([1, 2, 3], "1.0 + 2.0·H₁(x) + 3.0·H₂(x)"),
+ ([-1, 0, 3, -1], "-1.0 + 0.0·H₁(x) + 3.0·H₂(x) - 1.0·H₃(x)"),
+ (arange(12), ("0.0 + 1.0·H₁(x) + 2.0·H₂(x) + 3.0·H₃(x) + 4.0·H₄(x) + "
+ "5.0·H₅(x) +\n6.0·H₆(x) + 7.0·H₇(x) + 8.0·H₈(x) + "
+ "9.0·H₉(x) + 10.0·H₁₀(x) + 11.0·H₁₁(x)")),
+ ))
+ def test_hermite_str(self, inp, tgt):
+ res = str(poly.Hermite(inp))
+ assert_equal(res, tgt)
+
+ @pytest.mark.parametrize(('inp', 'tgt'), (
+ ([1, 2, 3], "1.0 + 2.0·He₁(x) + 3.0·He₂(x)"),
+ ([-1, 0, 3, -1], "-1.0 + 0.0·He₁(x) + 3.0·He₂(x) - 1.0·He₃(x)"),
+ (arange(12), ("0.0 + 1.0·He₁(x) + 2.0·He₂(x) + 3.0·He₃(x) + "
+ "4.0·He₄(x) + 5.0·He₅(x) +\n6.0·He₆(x) + 7.0·He₇(x) + "
+ "8.0·He₈(x) + 9.0·He₉(x) + 10.0·He₁₀(x) +\n"
+ "11.0·He₁₁(x)")),
+ ))
+ def test_hermiteE_str(self, inp, tgt):
+ res = str(poly.HermiteE(inp))
assert_equal(res, tgt)
- def test_legendre_str(self):
- res = str(poly.Legendre([0, 1]))
- tgt = 'leg([0. 1.])'
+ @pytest.mark.parametrize(('inp', 'tgt'), (
+ ([1, 2, 3], "1.0 + 2.0·L₁(x) + 3.0·L₂(x)"),
+ ([-1, 0, 3, -1], "-1.0 + 0.0·L₁(x) + 3.0·L₂(x) - 1.0·L₃(x)"),
+ (arange(12), ("0.0 + 1.0·L₁(x) + 2.0·L₂(x) + 3.0·L₃(x) + 4.0·L₄(x) + "
+ "5.0·L₅(x) +\n6.0·L₆(x) + 7.0·L₇(x) + 8.0·L₈(x) + "
+ "9.0·L₉(x) + 10.0·L₁₀(x) + 11.0·L₁₁(x)")),
+ ))
+ def test_laguerre_str(self, inp, tgt):
+ res = str(poly.Laguerre(inp))
assert_equal(res, tgt)
- def test_hermite_str(self):
- res = str(poly.Hermite([0, 1]))
- tgt = 'herm([0. 1.])'
+
+class TestStrAscii:
+
+ @pytest.fixture(scope='class', autouse=True)
+ def use_unicode(self):
+ poly.set_default_printstyle('ascii')
+
+ @pytest.mark.parametrize(('inp', 'tgt'), (
+ ([1, 2, 3], "1.0 + 2.0 x**1 + 3.0 x**2"),
+ ([-1, 0, 3, -1], "-1.0 + 0.0 x**1 + 3.0 x**2 - 1.0 x**3"),
+ (arange(12), ("0.0 + 1.0 x**1 + 2.0 x**2 + 3.0 x**3 + 4.0 x**4 + "
+ "5.0 x**5 + 6.0 x**6 +\n7.0 x**7 + 8.0 x**8 + "
+ "9.0 x**9 + 10.0 x**10 + 11.0 x**11")),
+ ))
+ def test_polynomial_str(self, inp, tgt):
+ res = str(poly.Polynomial(inp))
assert_equal(res, tgt)
- def test_hermiteE_str(self):
- res = str(poly.HermiteE([0, 1]))
- tgt = 'herme([0. 1.])'
+ @pytest.mark.parametrize(('inp', 'tgt'), (
+ ([1, 2, 3], "1.0 + 2.0 T_1(x) + 3.0 T_2(x)"),
+ ([-1, 0, 3, -1], "-1.0 + 0.0 T_1(x) + 3.0 T_2(x) - 1.0 T_3(x)"),
+ (arange(12), ("0.0 + 1.0 T_1(x) + 2.0 T_2(x) + 3.0 T_3(x) + "
+ "4.0 T_4(x) + 5.0 T_5(x) +\n6.0 T_6(x) + 7.0 T_7(x) + "
+ "8.0 T_8(x) + 9.0 T_9(x) + 10.0 T_10(x) +\n"
+ "11.0 T_11(x)")),
+ ))
+ def test_chebyshev_str(self, inp, tgt):
+ res = str(poly.Chebyshev(inp))
assert_equal(res, tgt)
- def test_laguerre_str(self):
- res = str(poly.Laguerre([0, 1]))
- tgt = 'lag([0. 1.])'
+ @pytest.mark.parametrize(('inp', 'tgt'), (
+ ([1, 2, 3], "1.0 + 2.0 P_1(x) + 3.0 P_2(x)"),
+ ([-1, 0, 3, -1], "-1.0 + 0.0 P_1(x) + 3.0 P_2(x) - 1.0 P_3(x)"),
+ (arange(12), ("0.0 + 1.0 P_1(x) + 2.0 P_2(x) + 3.0 P_3(x) + "
+ "4.0 P_4(x) + 5.0 P_5(x) +\n6.0 P_6(x) + 7.0 P_7(x) + "
+ "8.0 P_8(x) + 9.0 P_9(x) + 10.0 P_10(x) +\n"
+ "11.0 P_11(x)")),
+ ))
+ def test_legendre_str(self, inp, tgt):
+ res = str(poly.Legendre(inp))
assert_equal(res, tgt)
+ @pytest.mark.parametrize(('inp', 'tgt'), (
+ ([1, 2, 3], "1.0 + 2.0 H_1(x) + 3.0 H_2(x)"),
+ ([-1, 0, 3, -1], "-1.0 + 0.0 H_1(x) + 3.0 H_2(x) - 1.0 H_3(x)"),
+ (arange(12), ("0.0 + 1.0 H_1(x) + 2.0 H_2(x) + 3.0 H_3(x) + "
+ "4.0 H_4(x) + 5.0 H_5(x) +\n6.0 H_6(x) + 7.0 H_7(x) + "
+ "8.0 H_8(x) + 9.0 H_9(x) + 10.0 H_10(x) +\n"
+ "11.0 H_11(x)")),
+ ))
+ def test_hermite_str(self, inp, tgt):
+ res = str(poly.Hermite(inp))
+ assert_equal(res, tgt)
+
+ @pytest.mark.parametrize(('inp', 'tgt'), (
+ ([1, 2, 3], "1.0 + 2.0 He_1(x) + 3.0 He_2(x)"),
+ ([-1, 0, 3, -1], "-1.0 + 0.0 He_1(x) + 3.0 He_2(x) - 1.0 He_3(x)"),
+ (arange(12), ("0.0 + 1.0 He_1(x) + 2.0 He_2(x) + 3.0 He_3(x) + "
+ "4.0 He_4(x) +\n5.0 He_5(x) + 6.0 He_6(x) + "
+ "7.0 He_7(x) + 8.0 He_8(x) + 9.0 He_9(x) +\n"
+ "10.0 He_10(x) + 11.0 He_11(x)")),
+ ))
+ def test_hermiteE_str(self, inp, tgt):
+ res = str(poly.HermiteE(inp))
+ assert_equal(res, tgt)
+
+ @pytest.mark.parametrize(('inp', 'tgt'), (
+ ([1, 2, 3], "1.0 + 2.0 L_1(x) + 3.0 L_2(x)"),
+ ([-1, 0, 3, -1], "-1.0 + 0.0 L_1(x) + 3.0 L_2(x) - 1.0 L_3(x)"),
+ (arange(12), ("0.0 + 1.0 L_1(x) + 2.0 L_2(x) + 3.0 L_3(x) + "
+ "4.0 L_4(x) + 5.0 L_5(x) +\n6.0 L_6(x) + 7.0 L_7(x) + "
+ "8.0 L_8(x) + 9.0 L_9(x) + 10.0 L_10(x) +\n"
+ "11.0 L_11(x)")),
+ ))
+ def test_laguerre_str(self, inp, tgt):
+ res = str(poly.Laguerre(inp))
+ assert_equal(res, tgt)
+
+
+class TestLinebreaking:
+ poly.set_default_printstyle('ascii')
+
+ def test_single_line_one_less(self):
+ # With 'ascii' style, len(str(p)) is default linewidth - 1 (i.e. 74)
+ p = poly.Polynomial([123456789, 123456789, 123456789, 1234, 1])
+ assert_equal(len(str(p)), 74)
+ assert_equal(str(p), (
+ '123456789.0 + 123456789.0 x**1 + 123456789.0 x**2 + '
+ '1234.0 x**3 + 1.0 x**4'
+ ))
+
+ def test_num_chars_is_linewidth(self):
+ # len(str(p)) == default linewidth == 75
+ p = poly.Polynomial([123456789, 123456789, 123456789, 1234, 10])
+ assert_equal(len(str(p)), 75)
+ assert_equal(str(p), (
+ '123456789.0 + 123456789.0 x**1 + 123456789.0 x**2 + '
+ '1234.0 x**3 +\n10.0 x**4'
+ ))
+
+ def test_first_linebreak_multiline_one_less_than_linewidth(self):
+ # Multiline str where len(first_line) + len(next_term) == lw - 1 == 74
+ p = poly.Polynomial(
+ [123456789, 123456789, 123456789, 12, 1, 123456789]
+ )
+ assert_equal(len(str(p).split('\n')[0]), 74)
+ assert_equal(str(p), (
+ '123456789.0 + 123456789.0 x**1 + 123456789.0 x**2 + '
+ '12.0 x**3 + 1.0 x**4 +\n123456789.0 x**5'
+ ))
+
+ def test_first_linebreak_multiline_on_linewidth(self):
+ # First line is one character longer than previous test
+ p = poly.Polynomial(
+ [123456789, 123456789, 123456789, 123, 1, 123456789]
+ )
+ assert_equal(str(p), (
+ '123456789.0 + 123456789.0 x**1 + 123456789.0 x**2 + '
+ '123.0 x**3 +\n1.0 x**4 + 123456789.0 x**5'
+ ))
+
+ @pytest.mark.parametrize(('lw', 'tgt'), (
+ (75, ('0.0 + 10.0 x**1 + 200.0 x**2 + 3000.0 x**3 + 40000.0 x**4 +\n'
+ '500000.0 x**5 + 600000.0 x**6 + 70000.0 x**7 + 8000.0 x**8 + '
+ '900.0 x**9')),
+ (45, ('0.0 + 10.0 x**1 + 200.0 x**2 + 3000.0 x**3 +\n40000.0 x**4 + '
+ '500000.0 x**5 +\n600000.0 x**6 + 70000.0 x**7 + 8000.0 x**8 +\n'
+ '900.0 x**9')),
+ (132, ('0.0 + 10.0 x**1 + 200.0 x**2 + 3000.0 x**3 + 40000.0 x**4 + '
+ '500000.0 x**5 + 600000.0 x**6 + 70000.0 x**7 + 8000.0 x**8 + '
+ '900.0 x**9')),
+ ))
+ def test_linewidth_printoption(self, lw, tgt):
+ p = poly.Polynomial(
+ [0, 10, 200, 3000, 40000, 500000, 600000, 70000, 8000, 900]
+ )
+ with printoptions(linewidth=lw):
+ assert_equal(str(p), tgt)
+ for line in str(p).split('\n'):
+ assert_(len(line) < lw)
+
+
+def test_set_default_printoptions():
+ p = poly.Polynomial([1, 2, 3])
+ c = poly.Chebyshev([1, 2, 3])
+ poly.set_default_printstyle('ascii')
+ assert_equal(str(p), "1.0 + 2.0 x**1 + 3.0 x**2")
+ assert_equal(str(c), "1.0 + 2.0 T_1(x) + 3.0 T_2(x)")
+ poly.set_default_printstyle('unicode')
+ assert_equal(str(p), "1.0 + 2.0·x¹ + 3.0·x²")
+ assert_equal(str(c), "1.0 + 2.0·T₁(x) + 3.0·T₂(x)")
+ with pytest.raises(ValueError):
+ poly.set_default_printstyle('invalid_input')
+
+
+def test_complex_coefficients():
+ p = poly.Polynomial([0+1j, 1+1j, -2+2j, 3+0j])
+ poly.set_default_printstyle('unicode')
+ assert_equal(str(p), "1j + (1+1j)·x¹ - (2-2j)·x² + (3+0j)·x³")
+ poly.set_default_printstyle('ascii')
+ assert_equal(str(p), "1j + (1+1j) x**1 - (2-2j) x**2 + (3+0j) x**3")
+
+
+class TestFormat:
+ def test_format_unicode(self):
+ poly.Polynomial._use_unicode = False
+ p = poly.Polynomial([1, 2, 0, -1])
+ assert_equal(format(p, 'unicode'), "1.0 + 2.0·x¹ + 0.0·x² - 1.0·x³")
+
+ def test_format_ascii(self):
+ poly.Polynomial._use_unicode = True
+ p = poly.Polynomial([1, 2, 0, -1])
+ assert_equal(
+ format(p, 'ascii'), "1.0 + 2.0 x**1 + 0.0 x**2 - 1.0 x**3"
+ )
+
+ def test_empty_formatstr(self):
+ poly.Polynomial._use_unicode = False
+ p = poly.Polynomial([1, 2, 3])
+ assert_equal(format(p), "1.0 + 2.0 x**1 + 3.0 x**2")
+ assert_equal(f"{p}", "1.0 + 2.0 x**1 + 3.0 x**2")
+
+ def test_bad_formatstr(self):
+ p = poly.Polynomial([1, 2, 0, -1])
+ with pytest.raises(ValueError):
+ format(p, '.2f')
+
class TestRepr:
def test_polynomial_str(self):