项目作者: ayaanqui

项目描述 :
String based math expression resolver for Java
高级语言: Java
项目地址: git://github.com/ayaanqui/expression-resolver.git
创建时间: 2019-02-08T15:51:58Z
项目社区:https://github.com/ayaanqui/expression-resolver

开源协议:MIT License

下载


Expression Resolver

Build
Unit Tests

HitCount
License: 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

Function Description Inverse Parameter(s)
sin Sine (radians) arcsin n
cos Cosine (radians) arccos n
tan Tangent (radians) arctan n
sqrt Square root N/A n
ln Natural Log (log base e) exp n
log Log N/A n, base
deg Convert radians to degrees N/A n (radians)
rad Convert degrees to radians N/A n (degrees)
abs Absolute value N/A n
fact Factorial (!) N/A n (n >= 0)
avg Average N/A n1, ..., nk
sum Summation N/A n1, ..., 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

  1. <dependencies>
  2. ...
  3. <dependency>
  4. <groupId>com.github.ayaanqui</groupId>
  5. <artifactId>expression-resolver</artifactId>
  6. <version>2.0</version>
  7. </dependency>
  8. </dependencies>

Gradle

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

Usage

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

  1. import com.github.ayaanqui.expressionresolver.Resolver;
  2. import com.github.ayaanqui.expressionresolver.objects.Response;

Once these packages have been imported you can start using Resolver

  1. // Create ExpressionResolver object
  2. Resolver calculator = new Resolver();

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

  1. Resolver res = new Resolver();
  2. // First value
  3. double value1 = res
  4. .setExpression("473+5711-sin(20)"); // Returns Resolver object
  5. .solveExpression() // Returns Response object...
  6. .result; // Holds double value computed by solveExpression()
  7. // Second value
  8. double value2 = res
  9. .setExpression("sum(53, 577, 19493, 374)"); // Returns Resolver object
  10. .solveExpression() // Returns Response object...
  11. .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

  1. Resolver calculator = new Resolver();
  2. calculator.setExpression("2+2");
  3. double result = calculator.solveExpression().result; // 4
  4. calculator.setExpression("95-10+2^(3+3)*10");
  5. result = calculator.solveExpression().result; // 725.0
  6. calculator.setExpression("sin(20) + pi * 2");
  7. result = calculator.solveExpression().result; // 7.196130557907214

Accessing last result

Using the < operator allows access to the last successfull result

  1. Resolver calculator = new Resolver();
  2. calculator.setExpression("-pi^2");
  3. Response res = calculator.solveExpression();
  4. res.result // 9.869604401089358
  5. calculator.setExpression("2+<");
  6. calculator.solveExpression().result; // 11.869604401089358

Nested parentheses

Detects mismatched, or empty parentheses

  1. Resolver solver = new Resolver();
  2. solver.setExpression("1+((((((((((((1-1))))+2+2))))))))");
  3. double value = solver.solveExpression().result; // 5
  4. solver.setExpression("ln(((((((sin(tau/2))))))))-(((1+1)))");
  5. double v2 = solver.solveExpression().result; // -38.63870901270898
  6. // Mismatch parentheses error:
  7. solver.setExpression("(1-2)/sin((3*2)/2");
  8. Response res = solver.solveExpression();
  9. // Check for errors
  10. if (!res.success)
  11. 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)

  1. Resolver solver = new Resolver();
  2. // Declaring a new variable
  3. double v1 = solver.setExpression("force = 10*16.46")
  4. .solveExpression()
  5. .result; // 164.60000000000002
  6. // Using variable "force"
  7. // force = 164.60000000000002
  8. // pi = pre-defined π constant
  9. double v2 = solver.setExpression("force + pi")
  10. .solveExpression()
  11. .result; // 167.7415926535898
  12. // Results in an error (res.success = false)
  13. Response res = solver.setExpression("1 = 2").solveExpression();
  14. if (res.success == false)
  15. System.out.println("Error:\n" + res.errors[0] + "\n" + res.errors[1]);
  16. // Results in an error (res.success = false)
  17. // All variables are immutable (constant or unchangeable)
  18. Response res = solver.setExpression("pi = 3.142").solveExpression();
  19. if (res.success == false)
  20. 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.

  1. Resolver res = new Resolver();
  2. // Defining min function
  3. double minVal = res
  4. .setExpression("min(45, 9, 22, pi, 644, 004, 192)")
  5. // Name Function Definition
  6. .setFunction("min", params -> {
  7. double min = params[0];
  8. for (double val : params)
  9. if (val < min)
  10. min = val;
  11. return min;
  12. })
  13. .solveExpression().result; // pi
  14. // Defining force function
  15. double val = res
  16. .setFunction("force", params -> {
  17. return params[0] * params[1];
  18. })
  19. .setExpression("force(27, 10)")
  20. .solveExpression()
  21. .result;
  22. // Redfining built-in function arcsin
  23. res.setFunction("arcsin", params -> 1 / Math.sin(params[0]));