def test_vector(): # handling multiple input; each input is a vector; multiple functions x = AutoDiff([3, 1, 9], name='x') y = AutoDiff([5, 2, 4], name='y') f1 = (2 * x ** (-2)) + (3 * y ** 4) f2 = AutoDiff.cos(x + (4 * y ** 2)) v = Vector_Forward([f1, f2]) assert np.array_equal(v.val()[0], np.array([16877/9, np.cos(103)])) assert np.array_equal(v.val()[1], np.array([50, np.cos(17)])) assert np.array_equal(v.val()[2], np.array([62210/81, np.cos(73)])) index_x = v.jacobian()[0].index("x") index_y = v.jacobian()[0].index("y") assert np.array_equal(v.jacobian()[1][0][:, index_x], np.array([-4/27, -np.sin(103)])) assert np.array_equal(v.jacobian()[1][1][:, index_x], np.array([-4, -np.sin(17)])) assert np.array_equal(v.jacobian()[1][2][:, index_x], np.array([-4/729, -np.sin(73)])) assert np.array_equal(v.jacobian()[1][0][:, index_y], np.array([12*(5**3), -40*np.sin(103)])) assert np.array_equal(v.jacobian()[1][1][:, index_y], np.array([96, -16*np.sin(17)])) assert np.array_equal(v.jacobian()[1][2][:, index_y], np.array([12*(4**3), -32*np.sin(73)]))
def test_complicated_func(): tol = 1e-4 x = AutoDiff(2.0, name="x") f1 = AutoDiff.sin((AutoDiff.cos(x)**2.0 + x**2.0)**0.5) assert abs(f1.val - 0.890643) < tol assert abs(f1.der["x"] - (-0.529395)) < tol x = AutoDiff([1.0, 3.0, 5.0, 7.0], name="x") f2 = AutoDiff.sin(AutoDiff.ln(x) + (3 * x**2) + (2 * x) + 7) assert np.array_equal( f2.val, np.array([ np.sin(12), np.sin(40 + np.log(3)), np.sin(92 + np.log(5)), np.sin(168 + np.log(7)) ])) assert np.array_equal( f2.der["x"], np.array([ 9 * np.cos(12), 61 / 3 * np.cos(40 + np.log(3)), 161 / 5 * np.cos(92 + np.log(5)), 309 / 7 * np.cos(168 + np.log(7)) ])) x = AutoDiff([-1.0, -3.0, -5.0, -7.0, 0.1], name="x") f3 = AutoDiff.logistic(AutoDiff.tan(x) + (3 * x**(-2)) + (2 * x) + 7) assert np.less( abs(f3.val - np.array([ 1 / (1 + np.exp(np.tan(1) - 8)), 1 / (1 + np.exp(np.tan(3) - 4 / 3)), 1 / (1 + np.exp(np.tan(5) + 72 / 25)), 1 / (1 + np.exp(np.tan(7) + 340 / 49)), 1 ])), np.ones((5, 1)) * tol).all() assert np.less( abs(f3.der["x"] - np.array([0.018135, 0.49104, 3.40145666, 0.001531, 0])), np.ones((5, 1)) * tol).all()
def test_cos(): x = AutoDiff(5.0, 1.0, "x") f1 = 3 * x + 2 f2 = AutoDiff.cos(f1) assert f2.val == np.cos(17) assert f2.der["x"] == -3 * np.sin(17)