## "Fossies" - the Fresh Open Source Software Archive

### Member "numpy-1.16.4/numpy/lib/tests/test_polynomial.py" (14 May 2019, 10087 Bytes) of package /linux/misc/numpy-1.16.4.tar.gz:

As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. See also the last Fossies "Diffs" side-by-side code changes report for "test_polynomial.py": 1.16.2_vs_1.16.3.

```    1 from __future__ import division, absolute_import, print_function
2
3 import numpy as np
4 from numpy.testing import (
5     assert_, assert_equal, assert_array_equal, assert_almost_equal,
6     assert_array_almost_equal, assert_raises, assert_allclose
7     )
8
9
10 class TestPolynomial(object):
11     def test_poly1d_str_and_repr(self):
12         p = np.poly1d([1., 2, 3])
13         assert_equal(repr(p), 'poly1d([1., 2., 3.])')
14         assert_equal(str(p),
15                      '   2\n'
16                      '1 x + 2 x + 3')
17
18         q = np.poly1d([3., 2, 1])
19         assert_equal(repr(q), 'poly1d([3., 2., 1.])')
20         assert_equal(str(q),
21                      '   2\n'
22                      '3 x + 2 x + 1')
23
24         r = np.poly1d([1.89999 + 2j, -3j, -5.12345678, 2 + 1j])
25         assert_equal(str(r),
26                      '            3      2\n'
27                      '(1.9 + 2j) x - 3j x - 5.123 x + (2 + 1j)')
28
29         assert_equal(str(np.poly1d([-3, -2, -1])),
30                      '    2\n'
31                      '-3 x - 2 x - 1')
32
33     def test_poly1d_resolution(self):
34         p = np.poly1d([1., 2, 3])
35         q = np.poly1d([3., 2, 1])
36         assert_equal(p(0), 3.0)
37         assert_equal(p(5), 38.0)
38         assert_equal(q(0), 1.0)
39         assert_equal(q(5), 86.0)
40
41     def test_poly1d_math(self):
42         # here we use some simple coeffs to make calculations easier
43         p = np.poly1d([1., 2, 4])
44         q = np.poly1d([4., 2, 1])
45         assert_equal(p/q, (np.poly1d([0.25]), np.poly1d([1.5, 3.75])))
46         assert_equal(p.integ(), np.poly1d([1/3, 1., 4., 0.]))
47         assert_equal(p.integ(1), np.poly1d([1/3, 1., 4., 0.]))
48
49         p = np.poly1d([1., 2, 3])
50         q = np.poly1d([3., 2, 1])
51         assert_equal(p * q, np.poly1d([3., 8., 14., 8., 3.]))
52         assert_equal(p + q, np.poly1d([4., 4., 4.]))
53         assert_equal(p - q, np.poly1d([-2., 0., 2.]))
54         assert_equal(p ** 4, np.poly1d([1., 8., 36., 104., 214., 312., 324., 216., 81.]))
55         assert_equal(p(q), np.poly1d([9., 12., 16., 8., 6.]))
56         assert_equal(q(p), np.poly1d([3., 12., 32., 40., 34.]))
57         assert_equal(p.deriv(), np.poly1d([2., 2.]))
58         assert_equal(p.deriv(2), np.poly1d([2.]))
59         assert_equal(np.polydiv(np.poly1d([1, 0, -1]), np.poly1d([1, 1])),
60                      (np.poly1d([1., -1.]), np.poly1d([0.])))
61
62     def test_poly1d_misc(self):
63         p = np.poly1d([1., 2, 3])
64         assert_equal(np.asarray(p), np.array([1., 2., 3.]))
65         assert_equal(len(p), 2)
66         assert_equal((p[0], p[1], p[2], p[3]), (3.0, 2.0, 1.0, 0))
67
68     def test_poly1d_variable_arg(self):
69         q = np.poly1d([1., 2, 3], variable='y')
70         assert_equal(str(q),
71                      '   2\n'
72                      '1 y + 2 y + 3')
73         q = np.poly1d([1., 2, 3], variable='lambda')
74         assert_equal(str(q),
75                      '        2\n'
76                      '1 lambda + 2 lambda + 3')
77
78     def test_poly(self):
79         assert_array_almost_equal(np.poly([3, -np.sqrt(2), np.sqrt(2)]),
80                                   [1, -3, -2, 6])
81
82         # From matlab docs
83         A = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
84         assert_array_almost_equal(np.poly(A), [1, -6, -72, -27])
85
86         # Should produce real output for perfect conjugates
87         assert_(np.isrealobj(np.poly([+1.082j, +2.613j, -2.613j, -1.082j])))
88         assert_(np.isrealobj(np.poly([0+1j, -0+-1j, 1+2j,
89                                       1-2j, 1.+3.5j, 1-3.5j])))
90         assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j, 1+3j, 1-3.j])))
91         assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j])))
92         assert_(np.isrealobj(np.poly([1j, -1j, 2j, -2j])))
93         assert_(np.isrealobj(np.poly([1j, -1j])))
94         assert_(np.isrealobj(np.poly([1, -1])))
95
96         assert_(np.iscomplexobj(np.poly([1j, -1.0000001j])))
97
98         np.random.seed(42)
99         a = np.random.randn(100) + 1j*np.random.randn(100)
100         assert_(np.isrealobj(np.poly(np.concatenate((a, np.conjugate(a))))))
101
102     def test_roots(self):
103         assert_array_equal(np.roots([1, 0, 0]), [0, 0])
104
106         p = np.poly1d([4, 3, 2, 1])
107         p[3] = 0
108         assert_equal(str(p),
109                      "   2\n"
110                      "3 x + 2 x + 1")
111
112         p = np.poly1d([1, 2])
113         p[0] = 0
114         p[1] = 0
115         assert_equal(str(p), " \n0")
116
117     def test_polyfit(self):
118         c = np.array([3., 2., 1.])
119         x = np.linspace(0, 2, 7)
120         y = np.polyval(c, x)
121         err = [1, -1, 1, -1, 1, -1, 1]
122         weights = np.arange(8, 1, -1)**2/7.0
123
124         # Check exception when too few points for variance estimate. Note that
125         # the estimate requires the number of data points to exceed
126         # degree + 1
127         assert_raises(ValueError, np.polyfit,
128                       [1], [1], deg=0, cov=True)
129
130         # check 1D case
131         m, cov = np.polyfit(x, y+err, 2, cov=True)
132         est = [3.8571, 0.2857, 1.619]
133         assert_almost_equal(est, m, decimal=4)
134         val0 = [[ 1.4694, -2.9388,  0.8163],
135                 [-2.9388,  6.3673, -2.1224],
136                 [ 0.8163, -2.1224,  1.161 ]]
137         assert_almost_equal(val0, cov, decimal=4)
138
139         m2, cov2 = np.polyfit(x, y+err, 2, w=weights, cov=True)
140         assert_almost_equal([4.8927, -1.0177, 1.7768], m2, decimal=4)
141         val = [[ 4.3964, -5.0052,  0.4878],
142                [-5.0052,  6.8067, -0.9089],
143                [ 0.4878, -0.9089,  0.3337]]
144         assert_almost_equal(val, cov2, decimal=4)
145
146         m3, cov3 = np.polyfit(x, y+err, 2, w=weights, cov="unscaled")
147         assert_almost_equal([4.8927, -1.0177, 1.7768], m3, decimal=4)
148         val = [[ 0.1473, -0.1677,  0.0163],
149                [-0.1677,  0.228 , -0.0304],
150                [ 0.0163, -0.0304,  0.0112]]
151         assert_almost_equal(val, cov3, decimal=4)
152
153         # check 2D (n,1) case
154         y = y[:, np.newaxis]
155         c = c[:, np.newaxis]
156         assert_almost_equal(c, np.polyfit(x, y, 2))
157         # check 2D (n,2) case
158         yy = np.concatenate((y, y), axis=1)
159         cc = np.concatenate((c, c), axis=1)
160         assert_almost_equal(cc, np.polyfit(x, yy, 2))
161
162         m, cov = np.polyfit(x, yy + np.array(err)[:, np.newaxis], 2, cov=True)
163         assert_almost_equal(est, m[:, 0], decimal=4)
164         assert_almost_equal(est, m[:, 1], decimal=4)
165         assert_almost_equal(val0, cov[:, :, 0], decimal=4)
166         assert_almost_equal(val0, cov[:, :, 1], decimal=4)
167
168         # check order 1 (deg=0) case, were the analytic results are simple
169         np.random.seed(123)
170         y = np.random.normal(size=(4, 10000))
171         mean, cov = np.polyfit(np.zeros(y.shape[0]), y, deg=0, cov=True)
172         # Should get sigma_mean = sigma/sqrt(N) = 1./sqrt(4) = 0.5.
173         assert_allclose(mean.std(), 0.5, atol=0.01)
174         assert_allclose(np.sqrt(cov.mean()), 0.5, atol=0.01)
175         # Without scaling, since reduced chi2 is 1, the result should be the same.
176         mean, cov = np.polyfit(np.zeros(y.shape[0]), y, w=np.ones(y.shape[0]),
177                                deg=0, cov="unscaled")
178         assert_allclose(mean.std(), 0.5, atol=0.01)
179         assert_almost_equal(np.sqrt(cov.mean()), 0.5)
180         # If we estimate our errors wrong, no change with scaling:
181         w = np.full(y.shape[0], 1./0.5)
182         mean, cov = np.polyfit(np.zeros(y.shape[0]), y, w=w, deg=0, cov=True)
183         assert_allclose(mean.std(), 0.5, atol=0.01)
184         assert_allclose(np.sqrt(cov.mean()), 0.5, atol=0.01)
185         # But if we do not scale, our estimate for the error in the mean will
186         # differ.
187         mean, cov = np.polyfit(np.zeros(y.shape[0]), y, w=w, deg=0, cov="unscaled")
188         assert_allclose(mean.std(), 0.5, atol=0.01)
189         assert_almost_equal(np.sqrt(cov.mean()), 0.25)
190
191     def test_objects(self):
192         from decimal import Decimal
193         p = np.poly1d([Decimal('4.0'), Decimal('3.0'), Decimal('2.0')])
194         p2 = p * Decimal('1.333333333333333')
195         assert_(p2[1] == Decimal("3.9999999999999990"))
196         p2 = p.deriv()
197         assert_(p2[1] == Decimal('8.0'))
198         p2 = p.integ()
199         assert_(p2[3] == Decimal("1.333333333333333333333333333"))
200         assert_(p2[2] == Decimal('1.5'))
201         assert_(np.issubdtype(p2.coeffs.dtype, np.object_))
202         p = np.poly([Decimal(1), Decimal(2)])
203         assert_equal(np.poly([Decimal(1), Decimal(2)]),
204                      [1, Decimal(-3), Decimal(2)])
205
206     def test_complex(self):
207         p = np.poly1d([3j, 2j, 1j])
208         p2 = p.integ()
209         assert_((p2.coeffs == [1j, 1j, 1j, 0]).all())
210         p2 = p.deriv()
211         assert_((p2.coeffs == [6j, 2j]).all())
212
213     def test_integ_coeffs(self):
214         p = np.poly1d([3, 2, 1])
215         p2 = p.integ(3, k=[9, 7, 6])
216         assert_(
217             (p2.coeffs == [1/4./5., 1/3./4., 1/2./3., 9/1./2., 7, 6]).all())
218
219     def test_zero_dims(self):
220         try:
221             np.poly(np.zeros((0, 0)))
222         except ValueError:
223             pass
224
225     def test_poly_int_overflow(self):
226         """
227         Regression test for gh-5096.
228         """
229         v = np.arange(1, 21)
230         assert_almost_equal(np.poly(v), np.poly(np.diag(v)))
231
232     def test_poly_eq(self):
233         p = np.poly1d([1, 2, 3])
234         p2 = np.poly1d([1, 2, 4])
235         assert_equal(p == None, False)
236         assert_equal(p != None, True)
237         assert_equal(p == p, True)
238         assert_equal(p == p2, False)
239         assert_equal(p != p2, True)
240
241     def test_polydiv(self):
242         b = np.poly1d([2, 6, 6, 1])
243         a = np.poly1d([-1j, (1+2j), -(2+1j), 1])
244         q, r = np.polydiv(b, a)
245         assert_equal(q.coeffs.dtype, np.complex128)
246         assert_equal(r.coeffs.dtype, np.complex128)
247         assert_equal(q*a + r, b)
248
249     def test_poly_coeffs_mutable(self):
250         """ Coefficients should be modifiable """
251         p = np.poly1d([1, 2, 3])
252
253         p.coeffs += 1
254         assert_equal(p.coeffs, [2, 3, 4])
255
256         p.coeffs[2] += 10
257         assert_equal(p.coeffs, [2, 3, 14])
258
259         # this never used to be allowed - let's not add features to deprecated
260         # APIs
261         assert_raises(AttributeError, setattr, p, 'coeffs', np.array(1))
```