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

Related tags

Mathematics go golang
Overview

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

Issues
  • 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?

    opened by hiroxy 4
  • 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.

    opened by thecardinelli 2
  • 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

    opened by stevesmoot 1
  • 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.

    opened by ktye 0
  • 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

    opened by JJBordy 0
  • 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 } }

    opened by lx217197 0
Owner
Sonia Hamilton
Australian IT professional; ex-Google; ex gosnmp maintainer
Sonia Hamilton
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

Spring Engineering 4.1k Jun 23, 2022
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

Jake Brukhman 735 Jun 30, 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

Walter Schulze 484 Jun 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

Senseye 260 Jun 1, 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

Montana Flynn 2.5k Jun 26, 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

Sonia Hamilton 49 Jun 4, 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

Denis Bernard 27 Jun 19, 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

Denis Bernard 27 Jun 19, 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

Rob Pike 76 May 28, 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

Muhammad Soomro 0 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)

Konnor Klashinsky 0 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

Nathan Hedge 2 Apr 4, 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

HAH! Sun 7 Apr 6, 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

Caleb L. Power 1 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

Tadas Vilkeliskis 22 Mar 23, 2022
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

null 0 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

null 23 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

null 23 Feb 11, 2021
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

David Thole 0 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.

Restu Wahyu Saputra 24 Jun 4, 2022
A Jump Point Search Plus implement in Golang

Jump Point Search Plus 的 Golang 实现 JpsPlus 会对地图进行预处理,所以只适用于静态地图 BenchMark 两张地图,都

shameby 4 Jan 11, 2022
Simple expression evaluation engine for Go

??️ chili Currently in development, Unstable (API may change in future) Simple expression evaluation engine. Expression is one liner that evalutes int

Santhosh Kumar 71 Jun 21, 2022
Go native library for fast point tracking and K-Nearest queries

Geo Index Geo Index library Overview Splits the earth surface in a grid. At each cell we can store data, such as list of points, count of points, etc.

Hailo Network IP Ltd 340 May 26, 2022
:pushpin: State of the art point location and neighbour finding algorithms for region quadtrees, in Go

Region quadtrees in Go Region quadtrees and efficient neighbour finding techniques in Go Go-rquad proposes various implementations of region quadtrees

Aurélien Rainone 120 Jun 22, 2022
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

Spring Engineering 4.1k Jun 24, 2022
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

Spring Engineering 4.1k Jun 23, 2022
A Kubernetes Mutating Webhook to automatically re-point pod images to mirrors

kubernetes-mimic Kubernetes Mimic is a Mutating Webhook that will watch for pod creation and update events in a Kubernetes cluster and automatically a

null 5 Dec 1, 2021
Build a circular sector polygon feature spanning the angle between two given bearings, a center point and a radius. A pizza piece! 🍕

sectr ?? Build a circular sector polygon feature (pizza piece ?? ) spanning the angle between two given bearings, a radius and a center point. install

Ben 9 Mar 3, 2022
go-pry - an interactive REPL for Go that allows you to drop into your code at any point.

go-pry go-pry - an interactive REPL for Go that allows you to drop into your code at any point. Example Usage Install go-pry go get github.com/d4l3k/g

Tristan Rice 2.9k Jun 24, 2022