Skip to content

Latest commit

History

135 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Expression Resolver

BuildUnit TestsHitCountLicense: MIT

The Expression Resolver for Java provides a very easy way to solve any valid mathematical expression. The string based expression is parsed, and then reduced to a single numeric value. If the experssion was unable to reduce completely, the program tries to give clear error messages, such that the user is notified. (Note: The program escapes all whitespaces and $ signs)

Features

Built-in math operators

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Exponent: ^
  • Parentheses: ( and )

*Note: Numbers/Variables followed directly by ( sign do not get identified as multiplication. Therefore, they must be shown explicitly (Ex. use 2*(1+1) instead of 2(1+1)). However, this is not the case if a - sign is followed by (, -(2*1) is equivalent to -1*(2*1).

Built-in functions

FunctionDescriptionInverseParameter(s)
sinSine (radians)arcsinn
cosCosine (radians)arccosn
tanTangent (radians)arctann
sqrtSquare rootN/An
lnNatural Log (log base e)expn
logLogN/An, base
degConvert radians to degreesN/An (radians)
radConvert degrees to radiansN/An (degrees)
absAbsolute valueN/An
factFactorial (!)N/An (n >= 0)
avgAverageN/An1, ..., nk
sumSummationN/An1, ..., nk

Built-in mathematical constants

  • PI (π): pi (3.141592653589793)
  • Euler's number (e): e (2.718281828459045)
  • Tau (τ or 2*π): tau (6.283185307179586)

Set up

Apache Maven

<dependencies>
...
<dependency>
<groupId>com.github.ayaanqui</groupId>
<artifactId>expression-resolver</artifactId>
<version>2.0</version>
</dependency>
</dependencies>

Gradle

allprojects {
repositories {
...
maven { url "https://jitpack.io" }
}
}
dependencies {
...
implementation 'com.github.ayaanqui:expression-resolver:master-SNAPSHOT'
}

Usage

To set up ExpressionResolver, first make sure to import all necessary packages.

importcom.github.ayaanqui.expressionresolver.Resolver;
importcom.github.ayaanqui.expressionresolver.objects.Response;

Once these packages have been imported you can start using Resolver

// Create ExpressionResolver objectResolvercalculator = newResolver();

A Resolver object gives access to methods:

  • setExpression Takes in a string expression
  • setFunction Define function
  • expressionList
  • getExpression Returns expression set using setExpression
  • getLastResult Returns last successfully solved expression
  • solveExpression Solves the expression set using setExpression or expressionList. Returns Response object

Setting expressions

Resolverres = newResolver();
// First valuedoublevalue1 = res
.setExpression("473+5711-sin(20)"); // Returns Resolver object
.solveExpression() // Returns Response object...
.result; // Holds double value computed by solveExpression()// Second valuedoublevalue2 = res
.setExpression("sum(53, 577, 19493, 374)"); // Returns Resolver object
.solveExpression() // Returns Response object...
.result; // Holds double value computed by solveExpression()

Response object

This object is returned by solveExpression which holds all the information about the solved expression:

  • success Returns a boolean value indicating whether the expression was reduced without an error
    • true when the expression was reduced with no error
    • false when there was an error reducing the expression
  • result If success == true then result holds the double value of the reduced expression
  • errors If success == false then errors holds an String array (String[]) describing each error

Examples

Basic use case

Resolvercalculator = newResolver();
calculator.setExpression("2+2");
doubleresult = calculator.solveExpression().result; // 4calculator.setExpression("95-10+2^(3+3)*10");
result = calculator.solveExpression().result; // 725.0calculator.setExpression("sin(20) + pi * 2");
result = calculator.solveExpression().result; // 7.196130557907214

Accessing last result

Using the < operator allows access to the last successfull result

Resolvercalculator = newResolver();
calculator.setExpression("-pi^2");
Responseres = calculator.solveExpression();
res.result// 9.869604401089358calculator.setExpression("2+<");
calculator.solveExpression().result; // 11.869604401089358

Nested parentheses

Detects mismatched, or empty parentheses

Resolversolver = newResolver();
solver.setExpression("1+((((((((((((1-1))))+2+2))))))))");
doublevalue = solver.solveExpression().result; // 5solver.setExpression("ln(((((((sin(tau/2))))))))-(((1+1)))");
doublev2 = solver.solveExpression().result; // -38.63870901270898// Mismatch parentheses error:solver.setExpression("(1-2)/sin((3*2)/2");
Responseres = solver.solveExpression();
// Check for errorsif (!res.success)
System.out.println("Error: " + res.errors[0]); // Error: Parentheses mismatch

Variables

Assigned using the = operator. (Note: once a variable is assigned, the value cannot be changed)

Resolversolver = newResolver();
// Declaring a new variabledoublev1 = solver.setExpression("force = 10*16.46")
.solveExpression()
.result; // 164.60000000000002// Using variable "force"// force = 164.60000000000002// pi = pre-defined π constantdoublev2 = solver.setExpression("force + pi")
.solveExpression()
.result; // 167.7415926535898// Results in an error (res.success = false)Responseres = solver.setExpression("1 = 2").solveExpression();
if (res.success == false)
System.out.println("Error:\n" + res.errors[0] + "\n" + res.errors[1]);
// Results in an error (res.success = false)// All variables are immutable (constant or unchangeable)Responseres = solver.setExpression("pi = 3.142").solveExpression();
if (res.success == false)
System.out.println("Error:\n" + res.errors[0] + "\n" + res.errors[1]);

Defining functions

Functions can be defined by using setFunction method which takes two parameters: String function name, and Function<Double[], Double> function definition.

Resolverres = newResolver();
// Defining min functiondoubleminVal = res
.setExpression("min(45, 9, 22, pi, 644, 004, 192)")
// Name Function Definition
.setFunction("min", params -> {
doublemin = params[0];
for (doubleval : params)
if (val < min)
min = val;
returnmin;
})
.solveExpression().result; // pi// Defining force functiondoubleval = res
.setFunction("force", params -> {
returnparams[0] * params[1];
})
.setExpression("force(27, 10)")
.solveExpression()
.result;
// Redfining built-in function arcsinres.setFunction("arcsin", params -> 1 / Math.sin(params[0]));

About

String-based math expression evaluator Maven package

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages