예제 #1
0
        static void Main(string[] args)
        {
            // we will use a function of two variables
            Variable x = new Variable();
            Variable y = new Variable();

            // func(x, y) = (x + y) * exp(x - y)
            var func = (x + y) * TermBuilder.Exp(x - y);

            // create compiled term and use it for many gradient/value evaluations
            var compiledFunc = func.Compile(x, y);

            // we can now efficiently compute the gradient of "func" 64 times with different inputs.
            // compilation helps when we need many evaluations of the same function.
            for (int i = 0; i < 64; ++i)
            {
                var xVal = i / 64.0;
                var yVal = 1 + i / 128.0;

                var diffResult = compiledFunc.Differentiate(xVal, yVal);
                var gradient   = diffResult.Item1;
                var value      = diffResult.Item2;

                Console.WriteLine("The value of func at x = {0}, y = {1} is {2} and the gradient is ({3}, {4})",
                                  xVal, yVal, value, gradient[0], gradient[1]);
            }
        }
예제 #2
0
        static void Main(string[] args)
        {
            Variable x = new Variable();

            // f(x) = e^(-x) + x - 2
            // it has two roots. See plot.png image attached to this project.
            var func = TermBuilder.Exp(-x) + x - 2;

            // find the root near 2
            var root1 = RootFinder.NewtonRaphson(func, x, 2);

            // find the root near -1
            var root2 = RootFinder.NewtonRaphson(func, x, -1);

            Console.WriteLine("The equation e^(-x) + x - 2 = 0 has two solutions:\nx = {0}\nx = {1}", root1, root2);
        }
예제 #3
0
        static void Main(string[] args)
        {
            // we will use a function of two variables
            Variable x = new Variable();
            Variable y = new Variable();

            // func(x, y) = (x + y) * exp(x - y)
            var func = (x + y) * TermBuilder.Exp(x - y);

            // define the ordering of variables, and a point where the function will be evaluated/differentiated
            Variable[] vars  = { x, y };
            double[]   point = { 1, -2 };

            // calculate the value and the gradient at the point (x, y) = (1, -2)
            double eval = func.Evaluate(vars, point);

            double[] gradient = func.Differentiate(vars, point);

            // write the results
            Console.WriteLine("f(1, -2) = " + eval);
            Console.WriteLine("Gradient of f at (1, -2) = ({0}, {1})", gradient[0], gradient[1]);
        }
예제 #4
0
 public void ExpContract()
 {
     Assert.Throws <ArgumentNullException>(() => TermBuilder.Exp(null));
     Assert.IsType <Exp>(TermBuilder.Exp(x));
 }