def test_two_variables(): ad = AD(np.array([2, 2]), np.array([1, 1])) f1 = lambda x, y: Var.log(x)**Var.sin(y) assert AD.auto_diff(self=ad, func=f1) == Var( pytest.approx(0.7165772257590739), np.array([pytest.approx(0.47001694), pytest.approx(0.10929465)]))
def test_jac_matrix(): f1 = lambda x, y: Var.log(x)**Var.sin(y) f2 = lambda x, y: Var.sqrt(x) / y ad = AD(np.array([4.12, 5.13]), np.array([1, 1])) assert np.array_equal( ad.jac_matrix([f1, f2]), np.array([[pytest.approx(-0.11403015), pytest.approx(0.10263124)], [pytest.approx(0.048018), pytest.approx(-0.07712832)]]))
from EasyDiff.ad import AD from EasyDiff.var import Var from EasyDiff.rev_var import Rev_Var from EasyDiff.ad import AD_Mode import numpy as np # test forward mode. # give it a function of your choice func = lambda x, y: Var.log(x)**Var.sin(y) # give the initial values to take the derivatives at ad = AD(vals=np.array([2, 2]), ders=np.array([1, 1]), mode=AD_Mode.FORWARD) # calculate and print the derivatives print("Var.log(x) ** Var.sin(y): {}".format(vars(ad.auto_diff(func)))) # test reverse mode. func = lambda x, y: Rev_Var.log(x)**Rev_Var.sin(y) ad = AD(vals=np.array([2, 2]), ders=np.array([1, 1]), mode=AD_Mode.REVERSE) print("Rev_Var.log(x) ** Rev_Var.sin(y): {}".format(vars(ad.auto_diff(func))))
def test_two_variables(): ad = AD(np.array([2, 2]), np.array([1, 1]), AD_Mode.REVERSE) f1 = lambda x, y: Rev_Var.log(x) ** Rev_Var.sin(y) assert ad.vars[0].value == 2 assert ad.vars[1].value == 2 assert AD.auto_diff(self=ad,func=f1) == Var(pytest.approx(0.7165772257590739),np.array([pytest.approx(0.47001694),pytest.approx(0.10929465)]))
def test_single_variable(): ad = AD(np.array([2]), np.array([1]),AD_Mode.REVERSE) f1 = lambda x: Rev_Var.log(x) ** 2 assert AD.auto_diff(self=ad,func=f1) == Var(pytest.approx(0.4804530139182014),np.array([pytest.approx(0.69314718)]))