MCPcopy Create free account
hub / github.com/numpy/numpy / test_polyfit

Method test_polyfit

numpy/lib/tests/test_polynomial.py:136–208  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

134 assert_equal(str(p), " \n0")
135
136 def test_polyfit(self):
137 c = np.array([3., 2., 1.])
138 x = np.linspace(0, 2, 7)
139 y = np.polyval(c, x)
140 err = [1, -1, 1, -1, 1, -1, 1]
141 weights = np.arange(8, 1, -1)**2/7.0
142
143 # Check exception when too few points for variance estimate. Note that
144 # the estimate requires the number of data points to exceed
145 # degree + 1
146 assert_raises(ValueError, np.polyfit,
147 [1], [1], deg=0, cov=True)
148
149 # check 1D case
150 m, cov = np.polyfit(x, y+err, 2, cov=True)
151 est = [3.8571, 0.2857, 1.619]
152 assert_almost_equal(est, m, decimal=4)
153 val0 = [[ 1.4694, -2.9388, 0.8163],
154 [-2.9388, 6.3673, -2.1224],
155 [ 0.8163, -2.1224, 1.161 ]]
156 assert_almost_equal(val0, cov, decimal=4)
157
158 m2, cov2 = np.polyfit(x, y+err, 2, w=weights, cov=True)
159 assert_almost_equal([4.8927, -1.0177, 1.7768], m2, decimal=4)
160 val = [[ 4.3964, -5.0052, 0.4878],
161 [-5.0052, 6.8067, -0.9089],
162 [ 0.4878, -0.9089, 0.3337]]
163 assert_almost_equal(val, cov2, decimal=4)
164
165 m3, cov3 = np.polyfit(x, y+err, 2, w=weights, cov="unscaled")
166 assert_almost_equal([4.8927, -1.0177, 1.7768], m3, decimal=4)
167 val = [[ 0.1473, -0.1677, 0.0163],
168 [-0.1677, 0.228 , -0.0304],
169 [ 0.0163, -0.0304, 0.0112]]
170 assert_almost_equal(val, cov3, decimal=4)
171
172 # check 2D (n,1) case
173 y = y[:, np.newaxis]
174 c = c[:, np.newaxis]
175 assert_almost_equal(c, np.polyfit(x, y, 2))
176 # check 2D (n,2) case
177 yy = np.concatenate((y, y), axis=1)
178 cc = np.concatenate((c, c), axis=1)
179 assert_almost_equal(cc, np.polyfit(x, yy, 2))
180
181 m, cov = np.polyfit(x, yy + np.array(err)[:, np.newaxis], 2, cov=True)
182 assert_almost_equal(est, m[:, 0], decimal=4)
183 assert_almost_equal(est, m[:, 1], decimal=4)
184 assert_almost_equal(val0, cov[:, :, 0], decimal=4)
185 assert_almost_equal(val0, cov[:, :, 1], decimal=4)
186
187 # check order 1 (deg=0) case, were the analytic results are simple
188 np.random.seed(123)
189 y = np.random.normal(size=(4, 10000))
190 mean, cov = np.polyfit(np.zeros(y.shape[0]), y, deg=0, cov=True)
191 # Should get sigma_mean = sigma/sqrt(N) = 1./sqrt(4) = 0.5.
192 assert_allclose(mean.std(), 0.5, atol=0.01)
193 assert_allclose(np.sqrt(cov.mean()), 0.5, atol=0.01)

Callers

nothing calls this directly

Calls 6

assert_raisesFunction · 0.90
assert_almost_equalFunction · 0.90
assert_allcloseFunction · 0.90
linspaceMethod · 0.80
stdMethod · 0.45
meanMethod · 0.45

Tested by

no test coverage detected