def term_finite_gradient_d_ab_at_x(term, x, eps=1.e-5): tm = gaussian.term(term.a-eps,term.b).at_x(x) tp = gaussian.term(term.a+eps,term.b).at_x(x) gr_a = (tp-tm)/(2*eps) tm = gaussian.term(term.a,term.b-eps).at_x(x) tp = gaussian.term(term.a,term.b+eps).at_x(x) gr_b = (tp-tm)/(2*eps) return gaussian.term(gr_a, gr_b)
def term_finite_gradient_d_ab_at_x(term, x, eps=1.e-5): tm = gaussian.term(term.a - eps, term.b).at_x(x) tp = gaussian.term(term.a + eps, term.b).at_x(x) gr_a = (tp - tm) / (2 * eps) tm = gaussian.term(term.a, term.b - eps).at_x(x) tp = gaussian.term(term.a, term.b + eps).at_x(x) gr_b = (tp - tm) / (2 * eps) return gaussian.term(gr_a, gr_b)
def exercise_term(): t = gaussian.term(2,3) assert approx_equal(t.a, 2) assert approx_equal(t.b, 3) assert approx_equal(t.at_x_sq(4), 2*math.exp(-3*4)) assert approx_equal(t.at_x(2), 2*math.exp(-3*4)) eps = 1.e-5 for ix in (xrange(10)): x = ix/10. assert eps_eq((t.at_x(x+eps)-t.at_x(x-eps))/(2*eps), t.gradient_dx_at_x(x)) for f in [1,-1]: for t in [gaussian.term(f*2,3), gaussian.term(f*3,0), gaussian.term(f*4,1.e-4), gaussian.term(f*5,-1)]: exercise_gradient_dx(t) exercise_integral_dx(t) exercise_term_gradients_d_ab(t)
def exercise_term(): t = gaussian.term(2, 3) assert approx_equal(t.a, 2) assert approx_equal(t.b, 3) assert approx_equal(t.at_x_sq(4), 2 * math.exp(-3 * 4)) assert approx_equal(t.at_x(2), 2 * math.exp(-3 * 4)) eps = 1.e-5 for ix in (range(10)): x = ix / 10. assert eps_eq((t.at_x(x + eps) - t.at_x(x - eps)) / (2 * eps), t.gradient_dx_at_x(x)) for f in [1, -1]: for t in [ gaussian.term(f * 2, 3), gaussian.term(f * 3, 0), gaussian.term(f * 4, 1.e-4), gaussian.term(f * 5, -1) ]: exercise_gradient_dx(t) exercise_integral_dx(t) exercise_term_gradients_d_ab(t)