Exemplo n.º 1
0
def test_sin():
    x = Rev_Var(2.0)
    y = 2
    z = Rev_Var.sin(x)
    z.grad_value = 1
    assert z.value == pytest.approx(0.9092974268256817)
    assert x.grad() == pytest.approx(-0.4161468365471424)
    assert Rev_Var.sin(y) == np.sin(y)
Exemplo n.º 2
0
def test_rev_grad():
    x = Rev_Var(0.5)
    y = Rev_Var(4.2)
    z = x * y + Rev_Var.sin(x)
    z.grad_value = 1.0

    assert z.value == pytest.approx(2.579425538604203)
    assert x.grad() == pytest.approx(4.2 + np.cos(x.value))
    assert y.grad() == pytest.approx(0.5)
Exemplo n.º 3
0
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))))
Exemplo n.º 4
0
def test_jac_matrix():
	f1 = lambda x, y: Rev_Var.log(x) ** Rev_Var.sin(y)
	f2 = lambda x, y: Rev_Var.sqrt(x) / y
	ad = AD(np.array([4.12, 5.13]), np.array([1, 1]), AD_Mode.REVERSE)
	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)]]))
Exemplo n.º 5
0
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)]))