static void Main(string[] args) { // create function factory for arctangent var arctan = UnaryFunc.Factory( x => Math.Atan(x), // evaluate x => 1 / (1 + x * x)); // derivative of atan // create function factory for atan2 var atan2 = BinaryFunc.Factory( (x, y) => Math.Atan2(y, x), (x, y) => Tuple.Create( -y / (x * x + y * y), // d/dx (from wikipedia) x / (x * x + y * y))); // d/dy (from wikipedia) // define variables var u = new Variable(); var v = new Variable(); var w = new Variable(); // create and compile a term var term = atan2(u, v) - arctan(w) * atan2(v, w); var compiled = term.Compile(u, v, w); // compute value + gradient var diff = compiled.Differentiate(1, 2, -2); Console.WriteLine("The value at (1, 2, -2) is {0}", diff.Item2); Console.WriteLine("The gradient at (1, 2, -2) is ({0}, {1}, {2})", diff.Item1[0], diff.Item1[1], diff.Item1[2]); }
public void TestBinaryFuncSimple() { var v = Vec(new Variable(), new Variable()); var func = BinaryFunc.Factory( (x, y) => x * x - x * y, (x, y) => Tuple.Create(2 * x - y, -x)); var term = func(v[0], v[1]); var y1 = term.Evaluate(v, NumVec(1, 0)); // 1 - 0 = 1 var y2 = term.Evaluate(v, NumVec(0, 1)); // 0 - 0 = 0 var y3 = term.Evaluate(v, NumVec(1, 2)); // 1 - 2 = -1 Assert.Equal(1.0, y1); Assert.Equal(0.0, y2); Assert.Equal(-1.0, y3); }
public void TestBinaryFuncComplex() { var v = Vec(new Variable(), new Variable()); var func = BinaryFunc.Factory( (x, y) => x * x - x * y, (x, y) => Tuple.Create(2 * x - y, -x)); // f(x, y) = x² - xy - y² + xy = x² - y² var term = func(v[0], v[1]) - func(v[1], v[0]); var y1 = term.Evaluate(v, NumVec(1, 0)); // 1 - 0 = 1 var y2 = term.Evaluate(v, NumVec(0, 1)); // 0 - 1 = -1 var y3 = term.Evaluate(v, NumVec(2, 1)); // 4 - 1 = 3 Assert.Equal(1.0, y1); Assert.Equal(-1.0, y2); Assert.Equal(3.0, y3); }
public void DiffBinaryComplex() { var v = Vec(new Variable(), new Variable()); var func = BinaryFunc.Factory( (x, y) => x * x - x * y, (x, y) => Tuple.Create(2 * x - y, -x)); // f(x, y) = x² - xy - y² + xy = x² - y² // df/dx = 2x // df/dy = -2y var term = func(v[0], v[1]) - func(v[1], v[0]); var y1 = term.Differentiate(v, Vec(1.0, 0.0)); // (2, 0) var y2 = term.Differentiate(v, Vec(0.0, 1.0)); // (0, -2) var y3 = term.Differentiate(v, Vec(2.0, 1.0)); // (4, -2) Assert.Equal(Vec(2.0, 0.0), y1); Assert.Equal(Vec(0.0, -2.0), y2); Assert.Equal(Vec(4.0, -2.0), y3); }
public void DiffBinarySimple() { var v = Vec(new Variable(), new Variable()); var func = BinaryFunc.Factory( (x, y) => x * x - x * y, (x, y) => Tuple.Create(2 * x - y, -x)); // f(x, y) = x² - xy // df/dx = 2x - y // df/dy = -x var term = func(v[0], v[1]); var y1 = term.Differentiate(v, Vec(1.0, 0.0)); // (2, -1) var y2 = term.Differentiate(v, Vec(0.0, 1.0)); // (-1, 0) var y3 = term.Differentiate(v, Vec(1.0, 2.0)); // (0, -1) Assert.Equal(Vec(2.0, -1.0), y1); Assert.Equal(Vec(-1.0, 0.0), y2); Assert.Equal(Vec(0.0, -1.0), y3); }