Using the parse-evaluate pattern for high-performance calculations in a loop with a changing variable.

ID: 574

				
					using uCalcSoftware;

var uc = new uCalc();
// Define a variable 'x' that will be updated in the loop.
var variableX = uc.DefineVariable("x");

// Parse the expression just once before the loop begins.
var parsedExpr = uc.Parse("x^2 * 10");

Console.WriteLine("Evaluating 'x^2 * 10' for x = 1 to 5:");
for (double x = 1; x <= 5; x++) {
   variableX.Value(x);
   // Evaluate is very fast as the parsing work is already done.
   Console.WriteLine($"x = {x}, Result = {parsedExpr.Evaluate()}");
}
				
			
Evaluating 'x^2 * 10' for x = 1 to 5:
x = 1, Result = 10
x = 2, Result = 40
x = 3, Result = 90
x = 4, Result = 160
x = 5, Result = 250
				
					#include <iostream>
#include "uCalc.h"

using namespace std;
using namespace uCalcSoftware;

int main() {
   uCalc uc;
   // Define a variable 'x' that will be updated in the loop.
   auto variableX = uc.DefineVariable("x");

   // Parse the expression just once before the loop begins.
   auto parsedExpr = uc.Parse("x^2 * 10");

   cout << "Evaluating 'x^2 * 10' for x = 1 to 5:" << endl;
   for (double x = 1; x <= 5; x++) {
      variableX.Value(x);
      // Evaluate is very fast as the parsing work is already done.
      cout << "x = " << x << ", Result = " << parsedExpr.Evaluate() << endl;
   }
}
				
			
Evaluating 'x^2 * 10' for x = 1 to 5:
x = 1, Result = 10
x = 2, Result = 40
x = 3, Result = 90
x = 4, Result = 160
x = 5, Result = 250
				
					Imports System
Imports uCalcSoftware
Public Module Program
   Public Sub Main()
      Dim uc As New uCalc()
      '// Define a variable 'x' that will be updated in the loop.
      Dim variableX = uc.DefineVariable("x")
      
      '// Parse the expression just once before the loop begins.
      Dim parsedExpr = uc.Parse("x^2 * 10")
      
      Console.WriteLine("Evaluating 'x^2 * 10' for x = 1 to 5:")
      For x  As Double = 1 To 5
         variableX.Value(x)
         '// Evaluate is very fast as the parsing work is already done.
         Console.WriteLine($"x = {x}, Result = {parsedExpr.Evaluate()}")
      Next
   End Sub
End Module
				
			
Evaluating 'x^2 * 10' for x = 1 to 5:
x = 1, Result = 10
x = 2, Result = 40
x = 3, Result = 90
x = 4, Result = 160
x = 5, Result = 250