Implements a simple floating point arithmetic expression evaluator in Go (golang).

evaler

Build Status Coverage GoDoc https://github.com/soniah/evaler

Package evaler implements a simple floating point arithmetic expression evaluator.

Evaler uses Dijkstra's Shunting Yard algorithm to convert an infix expression to postfix/RPN format, then evaluates the RPN expression. The implementation is adapted from a Java implementation. The results are returned as a *big.Rat.

Usage

result, err := evaler.Eval("1+2")

Operators

The operators supported are:

+ - * / ^ ** () < > <= >= == !=

(^ and ** are both exponent operators)

Logical operators like < (less than) or > (greater than) get lowest precedence, all other precedence is as expected - BODMAS.

Logical tests like < and > tests will evaluate to 0.0 for false and 1.0 for true, allowing expressions like:

3 * (1 < 2) # returns 3.0
3 * (1 > 2) # returns 0.0

Minus implements both binary and unary operations.

See evaler_test.go for more examples of using operators.

Trigonometric Operators

The trigonometric operators supported are:

sin, cos, tan, ln, arcsin, arccos, arctan

For example:

cos(1)
sin(2-1)
sin(1)+2**2

See evaler_test.go for more examples of using trigonometric operators.

Variables

EvalWithVariables() allows variables to be passed into expressions, for example evaluate "x + 1", where x=5.

See evaler_test.go for more examples of using variables.

Issues

The math/big library doesn't have an exponent function ** and implenting one for big.Rat numbers is non-trivial. As a work around, arguments are converted to float64's, the calculation is done using the math.Pow() function, the result is converted to a big.Rat and placed back on the stack.

  • floating point numbers missing leading digits (like ".5 * 2") are failing - PR's welcome

Documentation

http://godoc.org/github.com/soniah/evaler

There are also a number of utility functions e.g. BigratToFloat(), BigratToInt() that may be useful when working with evaler.

Contributions

Contributions are welcome.

If you've never contributed to a Go project before here is an example workflow.

  1. fork this repo on the GitHub webpage
  2. go get github.com/soniah/evaler
  3. cd $GOPATH/src/github.com/soniah/evaler
  4. git remote rename origin upstream
  5. git remote add origin [email protected]:<your-github-username>/evaler.git
  6. git checkout -b development
  7. git push -u origin development (setup where you push to, check it works)

Author

Sonia Hamilton [email protected]

Dem Waffles [email protected] - trigonometric operators

License

Modified BSD License (BSD-3)

Links

[1] http://en.wikipedia.org/wiki/Shunting-yard_algorithm

[2] http://en.wikipedia.org/wiki/Reverse_Polish_notation

[3] http://willcode4beer.com/design.jsp?set=evalInfix

[4] http://www.mathsisfun.com/operation-order-bodmas.html

Owner
Sonia Hamilton
Australian IT professional; ex-Google; ex gosnmp maintainer
Sonia Hamilton
Comments
  • Support unary minus.

    Support unary minus.

    Hi @soniah

    I've enhanced the library to support unary minus. If this enhancement has worth for the library, could you review the code and merge it into master?

  • Add support for variables

    Add support for variables

    The Eval function should also accept a hashmap of string -> float64 for passing variables and their values in. This should use a symboltable under the covers.

    I will likely work on this feature.

  • fails w/o initial zeros

    fails w/o initial zeros

    .5 * 2 comes out as 10 fix is var fp_rx = regexp.MustCompile(([0-9]*\.?[0-9]+))
    I believe. (and add a test like): {".5 * 2", big.NewRat(1, 1), true}, // no leading zero

    tried to submit, but I clearly dont know how to use github yet...so submitting as issue. -s

  • Expression fails with wrong result

    Expression fails with wrong result

    This test case leads to a wrong result:

    {"2*6**3+4**6", big.NewRat(4528, 1), true},
    

    got 8624/1 expected 4528/1.

    https://www.google.com/search?q=2*6^3%2B4^6

    I think it's a problem in convert2postfix.

  • allow variable names to contain numbers

    allow variable names to contain numbers

    Unfortunately it gives an error if I try to pass a variable name which has a number in it; For example, a map with {"catX":"33"} evaluates fine; but if I pass: {"cat1":"33"} it says that there is no such variable "cat", ignoring the number in the name

    if there is no way to solve this, maybe indicate that in the "readme" file

  • pass two or more variables to expression,it doesn't work

    pass two or more variables to expression,it doesn't work

    for k := range symbolTable { s += k } symbols_rx = regexp.MustCompile(fmt.Sprintf("(%s)", s)) func Tokenis (expr string) []string { if symbols_rx != nil { spaced = symbols_rx.ReplaceAllString(spaced, " ${1} ")//it doesn't work } }

Related tags
Arbitrary-precision fixed-point decimal numbers in go

decimal Arbitrary-precision fixed-point decimal numbers in go. Note: Decimal library can "only" represent numbers with a maximum of 2^31 digits after

Jan 8, 2023
Naive Bayesian Classification for Golang.

Naive Bayesian Classification Perform naive Bayesian classification into an arbitrary number of classes on sets of strings. bayesian also supports ter

Dec 20, 2022
Parses the Graphviz DOT language in golang

Parses the Graphviz DOT language and creates an interface, in golang, with which to easily create new and manipulate existing graphs which can be writ

Dec 25, 2022
Golang RServe client. Use R from Go

Roger Roger is a Go RServe client, allowing the capabilities of R to be used from Go applications. The communication between Go and R is via TCP. It i

Dec 22, 2022
A well tested and comprehensive Golang statistics library package with no dependencies.

Stats - Golang Statistics Package A well tested and comprehensive Golang statistics library / package / module with no dependencies. If you have any s

Dec 27, 2022
Implements a simple floating point arithmetic expression evaluator in Go (golang).

evaler https://github.com/soniah/evaler Package evaler implements a simple floating point arithmetic expression evaluator. Evaler uses Dijkstra's Shun

Sep 27, 2022
An arbitrary-precision decimal floating-point arithmetic package for Go

decimal Package decimal implements arbitrary-precision decimal floating-point arithmetic for Go. Rationale How computers represent numbers internally

Sep 27, 2022
An arbitrary-precision decimal floating-point arithmetic package for Go

decimal Package decimal implements arbitrary-precision decimal floating-point arithmetic for Go. Rationale How computers represent numbers internally

Sep 27, 2022
A simple evaluator for arithmetic integer expressions.

The expr package provides a simple evaluator for arithmetic integer expressions. The syntax and operations are the same as in Go. Operands are the nat

Dec 13, 2022
Client-Server Expression Evaluator with Persistent Database Support (Redis & SQL)

Client-Server-Expression-Evaluator Client-Server Expression Evaluator with Persistent Database Support (Redis & SQL). Client-Server Expression Evaluat

Jan 4, 2022
Utilities for rounding and truncating floating point numbers.

Rounders Provides utilities for rounding and truncating floating point numbers. Example: rounders.RoundToDecimals(12.48881, 2)

Jan 6, 2022
It's a basic newtonian gravity simulation written in Go using floating point numbers with 1024 bits of accuracy

Float 1K Gravity What is it? It's a basic newtonian gravity simulation written in Go using floating point numbers with 1024 bits of accuracy. It is cu

Dec 13, 2022
An anonymous, encrypted Point-to-Point (Layer 3) tunnel between two peers.

NKN-Link An anonymous, encrypted Point-to-Point (Layer 3) tunnel between two peers. NKN-Link Table of Contents Preface Description Install Setup Run P

Dec 20, 2022
Wg-configurator - This project makes it easier to configure a fleet of servers interconnected via the WireGuard point-to-point virtual private network.

WireGuard Configurator This project makes it easier to configure a fleet of servers interconnected via the WireGuard point-to-point virtual private ne

Mar 29, 2022
conditiond is a generic constraint and policy evaluator.

conditiond conditiond is a generic constraint and policy evaluator. This tool lets you define constraints in data and evaluate them at run time. It's

Dec 5, 2022
Assigns floating ip addresses to Rancher Guest clusters.
Assigns floating ip addresses to Rancher Guest clusters.

kube-fip-operator The kube-fip-operator application manages the FloatingIP and FloatingIPRange Custom Resource Definition objects in a Rancher environ

Dec 6, 2021
Simple web framework for go, still quite beta at this point

WFDR Framework - Beta Release New 18/Feb/2012: Updated for go 1.0, new directory layout to take advantage of the go build tool. Background There's a m

Feb 11, 2021
Simple web framework for go, still quite beta at this point

WFDR Framework - Beta Release New 18/Feb/2012: Updated for go 1.0, new directory layout to take advantage of the go build tool. Background There's a m

Feb 11, 2021
A simple application, demo at this point, on how to pull a backup from Collibra on prem (say for Cohesity backup)
A simple application, demo at this point, on how to pull a backup from Collibra on prem (say for Cohesity backup)

go-get-collibra-backup Introduction This repository is a very simple go application that's intended, at this point, more of a demonstration about how

Dec 10, 2021
Example Golang API backend rest implementation mini project Point Of Sale using Gin Framework and Gorm ORM Database.

Example Golang API backend rest implementation mini project Point Of Sale using Gin Framework and Gorm ORM Database.

Dec 23, 2022