• notice
  • Congratulations on the launch of the Sought Tech site

Execute mathematical string expressions in Java

1 Overview

In this tutorial, we will discuss various methods of executing mathematical string expressions using Java. This feature may come in handy in projects where we want to execute mathematical expressions provided in string format.

First, we will discuss some third-party libraries and their usage. Next, we will see how to use the built-in Java Scripting API to accomplish this task.

2.exp4j

exp4j is an open source library that can be used to evaluate mathematical expressions and functions. The library implements Dijkstra's Shutting Yard algorithm, which is a method of parsing mathematical expressions specified by infix symbols .

In addition to using standard operators and functions, exp4j also allows us to create custom operators and functions.

2.1. Add Maven dependency

To use exp4j, we need to add Maven dependencies to the project :

<dependency>
<groupId>net.objecthunter</groupId>
<artifactId>exp4j</artifactId>
<version>0.4.8</version>
</dependency>

2.2. Evaluate simple expressions

We can evaluate Stringsimple mathematical expressions provided in the format:

@Test
public void givenSimpleExpression_whenCallEvaluateMethod_thenSuccess() {
Expression expression = new ExpressionBuilder("3+2").build();
double result = expression.evaluate();
Assertions.assertEquals(5, result);
}

In the above code snippet, we first create an ExpressionBuilderinstance. Then, assign it to a Expressionreference, and the expression is used to evaluate the expression.

2.3. Use variables in expressions

Now that we know how to calculate simple expressions, let's add some variables to the expression:

@Test
public void givenTwoVariables_whenCallEvaluateMethod_thenSuccess() {
Expression expression = new ExpressionBuilder("3x+2y")
.variables("x", "y")
.build()
.setVariable("x", 2)
.setVariable("y", 3);
double result = expression.evaluate();
Assertions.assertEquals(12, result);
}

In the above example, we use the variablesmethod to introduce two variables xand y,Using this method , we can add the required number of variables to the expression After declaring variables, you can setVariableassign values to them using methods.

2.4. Evaluate expressions containing mathematical functions

Let us now look at a short example of how to evaluate some standard mathematical functions:

@Test
public void givenMathFunctions_whenCallEvaluateMethod_thenSuccess() {
Expression expression = new ExpressionBuilder("sin(x)*sin(x)+cos(x)*cos(x)")
.variables("x")
.build()
.setVariable("x", 0.5);
double result = expression.evaluate();
Assertions.assertEquals(1, result);
}

3.Javaluator

Javaluator is another free lightweight independent library. Like exp4j, Javaluator is also used to evaluate infix expressions .

3.1. Add Maven dependency

We can use Javaluator in the project with the following Maven dependencies :

<dependency>
<groupId>com.fathzer</groupId>
<artifactId>javaluator</artifactId>
<version>3.0.3</version>
</dependency>

3.2. Evaluate simple expressions

To use Javaluator to evaluate expressions, we first need to create DoubleEvaluatoran instance:

@Test
public void givenExpression_whenCallEvaluateMethod_thenSuccess() {
String expression = "3+2";
DoubleEvaluator eval = new DoubleEvaluator();
Double result = eval.evaluate(expression);
Assertions.assertEquals(5, result);
}

3.3. Evaluate expressions containing variables

To evaluate expressions containing variables, we use StaticVariableSet:

@Test
public void givenVariables_whenCallEvaluateMethod_thenSuccess() {
String expression = "3*x+2*y";
DoubleEvaluator eval = new DoubleEvaluator();
StaticVariableSet<Double> variables = new StaticVariableSet<Double>();
variables.set("x", 2.0);
variables.set("y", 3.0);
Double result = eval.evaluate(expression, variables);
Assertions.assertEquals(12, result);
}

Then, we use StaticVariableSet#setmethods to assign values to variables.

3.4. Evaluate expressions containing mathematical functions

We can also use the Javaluator library to solve expressions containing mathematical functions:

@Test
public void givenMathFunction_whenCallEvaluateMethod_thenSuccess() {
String expression = "sin(x)*sin(x)+cos(x)*cos(x)";
DoubleEvaluator eval = new DoubleEvaluator();
StaticVariableSet<Double> variables = new StaticVariableSet<Double>();
variables.set("x", 0.5);
Double result = eval.evaluate(expression, variables);
Assertions.assertEquals(1, result);
}

4.Java Script API

Now that we have discussed third-party libraries, let's now discuss how to use the built-in API for this purpose. Java already comes with a small but powerful scripting API. All classes and interfaces of this API are in the javax.scriptpackage.

It contains ScriptEngineManagerand ScriptEngineinterfaces so that we can evaluate JavaScript. Before Java 8, the Rhinoengine came with Java. However, starting with Java 8, Java comes with an updated and more powerful Nashorn engine.

4.1. Get an ScriptEngineinstance

To create ScriptEngine, we must first create ScriptEngineManageran instance. After we have the instance, we need to call the ScriptEngineManager#getEngineByNamemethod to get ScriptEngine:

ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");

Please note that it Nashornis the default JavaScript engine included with the JDK.

4.2. Evaluate simple expressions

Now, we can use the above scriptEngineinstance to call the ScriptEngine#evalmethod:

String expression = "3+2";
Integer result = (Integer) scriptEngine.eval(expression);
Assertions.assertEquals(5, result);

4.3. Evaluate expressions containing variables

To evaluate expressions containing variables, we need to declare and initialize variables:

String expression = "x=2; y=3; 3*x+2*y;";
Double result = (Double) scriptEngine.eval(expression);
Assertions.assertEquals(12, result);

Since we are using a JavaScript engine, we can directly add variables to expressions just like in JavaScript .

**Note-JavaScript has no direct way to perform mathematical operations and requires access to Mathobjects. Therefore, we cannot use the Java Scripting API to solve mathematical expressions.
**

5 Conclusion

In this article, we have seen various techniques for evaluating mathematical expressions using Java.


Tags

Technical otaku

Sought technology together

Related Topic

1 Comments

author

order lipitor 10mg online cheap & lt;a href="https://lipiws.top/"& gt;order generic lipitor 40mg& lt;/a& gt; order atorvastatin 40mg

Ibxvho

2024-03-09

Leave a Reply

+