Code Monkey home page Code Monkey logo

exprk's Introduction

ExprK

A simple mathematical expression evaluator for Kotlin and Java, written in Kotlin.

Features:

  • Uses BigDecimal for calculations and results
  • Allows you to define variables using values or expressions
  • Variable definition expressions can reference previously defined variables
  • Configurable precision and rounding mode
  • Functions and the ability to define new ones

Supported operators

Arithmetic operators

Name Operator
Plus +
Minus -
Multiply *
Divide /
Modulus %
Exponent ^
Square root โˆš

Logical operators

Name Operator
And &&
Or ||

Pre-defined variables

Variable Value
pi 3.141592653589793
e 2.718281828459045

Pre-defined functions

Function Description
abs(expression) Returns the absolute value of the expression
sum(expression, ...) Returns the sum of all arguments
floor(expression) Rounds the value of the expression down to the nearest integer
ceil(expression) Rounds the value of the expression up to the nearest integer
round(expression) Rounds the value of the expression to the nearest integer in the direction decided by the configured rounding mode
min(expression, ...) Returns the value of the smallest argument
max(expression, ...) Returns the value of the largest argument
if(condition, trueValue, falseValue) Returns trueValue if condition is true(condition != 0), otherwise it returns falseValue

Examples:

val result = Expressions()
    .eval("(5+5)*10") // returns 100

You can define variables with the define method.

val result = Expressions()
    .define("x", 5)
    .eval("x*10") // returns 50

The define method returns the expression instance to allow chaining definition method calls together.

val result = Expressions()
    .define("x", 5)
    .define("y", "5*2")
    .eval("x*y") // returns 50

Variable definition expressions can reference previously defined variables.

val result = Expressions()
    .define("x", 5)
    .define("y", "x^2")
    .eval("y*x") // returns 125

You can add new functions with the addFunction method.

val result = Expressions()
    .addFunction("min") { arguments ->
        if (arguments.isEmpty()) throw ExpressionException(
                "min requires at least one argument")

        arguments.min()!!
    }
    .eval("min(4, 8, 16)") // returns 4

You can set the precision and rounding mode with setPrecision and setRoundingMode.

val result = Expressions()
    .setPrecision(128)
    .setRoundingMode(RoundingMode.UP)
    .eval("222^3/5.5") 

exprk's People

Contributors

dependabot[bot] avatar jinan159 avatar keelar avatar sadellie avatar tblakers avatar wireless4024 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

exprk's Issues

Evaluator should be public

It should be possible to obtain and configure an Evaluator separately from Expressions, so different functions/constants/etc. can be configured.

(This will also require Expr and its various subclasses, probably Parser, and likely other interfaces and classes to be made public. I honestly don't see much reason to restrict visibility of much in the library, it's already nice and tight. IMO the easiest fix is just to make everything public.)

Undefined variable

Hi
Is it possible to define string expression:

e.g:
expressions.define("x", "durim")

Can i configure exponential usage in result?

first of all, Thank you for your code!

my question is that how can i configure exponential result?
for example, the result is 10.01+E3 for 10000+10. I want to use exponential only for much larger numbers.

Thank you again.

๐Ÿ› Exponential operator(^) does not throw exception about overflow

First of all, thanks for your code.
I found a bug, and would like to report it

It's about exponential(^) operation between two bigDecimal number.
I think that a calculation which expected to take a long time to calculate must throw exception about overflow.
e.g.
Expressions().eval("34^3.0E+24")
Expressions().eval("34^3.0E+2451223111")

The code above throw exception about overflow.
But below is not
34^3.0E+2451223

I think it has to have some validation about each power calculation.
Thank you

Change arguments.min()!! and arguments.max()!! with arguments.minOrNull()!! and arguments.maxAndNull() in Expressions.kt

arguments.min()!! and arguments.max()!! throw error in recent kotlin versions. Consider changing it with arguments.minOrNull()!! and arguments.maxAndNull()!! in

Replace this part of the code:

Expressions.kt

 evaluator.addFunction("min", object : Function() {
            override fun call(arguments: List<BigDecimal>): BigDecimal {
                if (arguments.isEmpty()) throw ExpressionException(
                        "min requires at least one argument")

                return arguments.min()!!
            }
        })

        evaluator.addFunction("max", object : Function() {
            override fun call(arguments: List<BigDecimal>): BigDecimal {
                if (arguments.isEmpty()) throw ExpressionException(
                        "max requires at least one argument")

                return arguments.max()!!
            }
        })

with this:

Expressions.kt

 evaluator.addFunction("min", object : Function() {
            override fun call(arguments: List<BigDecimal>): BigDecimal {
                if (arguments.isEmpty()) throw ExpressionException(
                        "min requires at least one argument")

                return arguments.minOrNull()!!
            }
        })

        evaluator.addFunction("max", object : Function() {
            override fun call(arguments: List<BigDecimal>): BigDecimal {
                if (arguments.isEmpty()) throw ExpressionException(
                        "max requires at least one argument")

                return arguments.maxOrNull()!!
            }
        })

Parse error when BigDecimal contains scientific notation

This unit test:

    @Test
    fun `test that scientific notation BigDecimals are parsed and equivalent to the plain representation`() {
        val expr = Expressions()
        val scival = BigDecimal("1E+7")
        expr.define("SCIVAL", scival)
        assertEquals(scival.toPlainString(), expr.eval("SCIVAL").toPlainString())
    }

Produces this result:

com.github.keelar.exprk.ExpressionException: Expected end of expression, found 'E'

	at com.github.keelar.exprk.internal.Parser.parse(Parser.kt:15)
	at com.github.keelar.exprk.Expressions.parse(Expressions.kt:173)
	at com.github.keelar.exprk.Expressions.parse(Expressions.kt:169)
	at com.github.keelar.exprk.Expressions.define(Expressions.kt:141)
	at com.github.keelar.exprk.Expressions.define(Expressions.kt:135)
	at com.github.keelar.exprk.TestExpressions.test that scientific notation BigDecimals are parsed and equivalent to the plain representation(TestExpressions.kt:13)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.