Home

Tutorial

Table of contents:

Using built-in evaluator

Working with variables

A very common need is to evaluate expressions that contains variables.
Imagine, for example, that you want to plot the function sin(x) between 0 and pi/2.

First, create a standard real expressions evaluator. DoubleEvaluator eval = new DoubleEvaluator();

Then declare the expression you want to evaluate String expression = "sin(x)";

Now, you will have to evaluate that expression in a loop and increasing the x value at each step.
The AbstractEvaluator.evaluate method allows you to provide an evaluation context to the evaluator.
We will use an evaluation context that implements AbstractVariableSet in order to pass the values of x to the evaluator.
Javaluator provides you with a concrete implementation which is sufficient in most cases: The StaticVariableSet.
Simply create such a variable set with its default construtor. StaticVariableSet<Double> variables = new StaticVariableSet<Double>()

In each loop, it then remains to declare the new value for x and evaluate the expression

double x = 0;
double step = Math.PI/8;
while (x<=Math.PI/2) {
  // Set the value of x
  variables.set("x", x);
  // Evaluate the expression
  Double result = eval.evaluate(expression, variables);
  // Ouput the result
  ...
  x += step;
}


Here is the complete sample code:

package com.fathzer.soft.javaluator.examples;
 
import com.fathzer.soft.javaluator.DoubleEvaluator;
import com.fathzer.soft.javaluator.StaticVariableSet;
 
/** An example of how to use variables in evaluators.
 * <br>This example outputs the values of <i>sin(x)</i> for many values of x between 0 and pi/2.
 */
public class Variables {
  public static void main(String[] args) {
    final String expression = "sin(x)"; // Here is the expression to evaluate
    // Create the evaluator
    final DoubleEvaluator eval = new DoubleEvaluator();
    // Create a new empty variable set
    final StaticVariableSet<Double> variables = new StaticVariableSet<Double>();
    double x = 0;
    final double step = Math.PI/8;
    while (x<=Math.PI/2) {
      // Set the value of x
      variables.set("x", x);
      // Evaluate the expression
      Double result = eval.evaluate(expression, variables);
      // Ouput the result
      System.out.println("x="+x+" -> "+expression+" = "+result);
      x += step;
    }
  }
}
 

The output is

x=0.0 -> sin(x) = 0.0
x=0.39269908169872414 -> sin(x) = 0.3826834323650898
x=0.7853981633974483 -> sin(x) = 0.7071067811865475
x=1.1780972450961724 -> sin(x) = 0.9238795325112867
x=1.5707963267948966 -> sin(x) = 1.0

Advertising

Back to top