388
388
return x*(x - 1)*(x - 2)
391
return x**4 + x**2 + 1
390
393
# Test exceptions
391
394
assert_raises(ValueError, herm.hermfit, [1], [1], -1)
392
395
assert_raises(TypeError, herm.hermfit, [[1]], [1], 0)
396
399
assert_raises(TypeError, herm.hermfit, [1], [1, 2], 0)
397
400
assert_raises(TypeError, herm.hermfit, [1], [1], 0, w=[[1]])
398
401
assert_raises(TypeError, herm.hermfit, [1], [1], 0, w=[1, 1])
402
assert_raises(ValueError, herm.hermfit, [1], [1], [-1,])
403
assert_raises(ValueError, herm.hermfit, [1], [1], [2, -1, 6])
404
assert_raises(TypeError, herm.hermfit, [1], [1], [])
401
407
x = np.linspace(0, 2)
404
410
coef3 = herm.hermfit(x, y, 3)
405
411
assert_equal(len(coef3), 4)
406
412
assert_almost_equal(herm.hermval(x, coef3), y)
413
coef3 = herm.hermfit(x, y, [0, 1, 2, 3])
414
assert_equal(len(coef3), 4)
415
assert_almost_equal(herm.hermval(x, coef3), y)
408
417
coef4 = herm.hermfit(x, y, 4)
409
418
assert_equal(len(coef4), 5)
410
419
assert_almost_equal(herm.hermval(x, coef4), y)
420
coef4 = herm.hermfit(x, y, [0, 1, 2, 3, 4])
421
assert_equal(len(coef4), 5)
422
assert_almost_equal(herm.hermval(x, coef4), y)
423
# check things still work if deg is not in strict increasing
424
coef4 = herm.hermfit(x, y, [2, 3, 4, 1, 0])
425
assert_equal(len(coef4), 5)
426
assert_almost_equal(herm.hermval(x, coef4), y)
412
428
coef2d = herm.hermfit(x, np.array([y, y]).T, 3)
413
429
assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
430
coef2d = herm.hermfit(x, np.array([y, y]).T, [0, 1, 2, 3])
431
assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
415
433
w = np.zeros_like(x)
419
437
wcoef3 = herm.hermfit(x, yw, 3, w=w)
420
438
assert_almost_equal(wcoef3, coef3)
439
wcoef3 = herm.hermfit(x, yw, [0, 1, 2, 3], w=w)
440
assert_almost_equal(wcoef3, coef3)
422
442
wcoef2d = herm.hermfit(x, np.array([yw, yw]).T, 3, w=w)
423
443
assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
444
wcoef2d = herm.hermfit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)
445
assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
424
446
# test scaling with complex values x points whose square
425
447
# is zero when summed.
426
448
x = [1, 1j, -1, -1j]
427
449
assert_almost_equal(herm.hermfit(x, x, 1), [0, .5])
450
assert_almost_equal(herm.hermfit(x, x, [0, 1]), [0, .5])
451
# test fitting only even Legendre polynomials
452
x = np.linspace(-1, 1)
454
coef1 = herm.hermfit(x, y, 4)
455
assert_almost_equal(herm.hermval(x, coef1), y)
456
coef2 = herm.hermfit(x, y, [0, 2, 4])
457
assert_almost_equal(herm.hermval(x, coef2), y)
458
assert_almost_equal(coef1, coef2)
430
461
class TestCompanion(TestCase):