Implements a simple floating point arithmetic expression evaluator in 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

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?

    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
Package goraph implements graph data structure and algorithms.

goraph Package goraph implements graph data structure and algorithms. go get -v gopkg.in/gyuho/goraph.v2; I have tutorials and visualizations of grap

Gyuho Lee 699 Nov 18, 2022
An ordinary differential equation solving library in golang.

ode An ordinary differential equation solving library in golang. Features Multi-dimensional state vector (i.e. extended states) Channel based stopping

Chris 20 Oct 19, 2022
Types and utilities for working with 2d geometry in Golang

orb Package orb defines a set of types for working with 2d geo and planar/projected geometric data in Golang. There are a set of sub-packages that use

Paul Mach 604 Dec 7, 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.6k Dec 3, 2022
:wink: :cyclone: :strawberry: TextRank implementation in Golang with extendable features (summarization, phrase extraction) and multithreading (goroutine) support (Go 1.8, 1.9, 1.10)

TextRank on Go This source code is an implementation of textrank algorithm, under MIT licence. The minimum requred Go version is 1.8. MOTIVATION If th

David Belicza 167 Nov 27, 2022
Golang evasion tool, execute-assembly .Net file

?? Frog For Automatic Scan ?? Doge For Defense Evasion&Offensive Security Doge-Assembly Golang evasion tool, execute-assembly .Net file Intro Are you

TimWhite 83 Nov 22, 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 50 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

Denis Bernard 29 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

Denis Bernard 29 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

Rob Pike 80 Sep 6, 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