Evaluate formula in Go

go-exprtk package will probably meet all kinds of your needs to evaluate any kind of mathematical expression dynamically.

package main

import (
    "fmt"

    "github.com/Pramod-Devireddy/go-exprtk"
)

func main() {
    exprtkObj := exprtk.NewExprtk()

    exprtkObj.SetExpression("(x + 2) / 10")

    exprtkObj.AddDoubleVariable("x")

    exprtkObj.CompileExpression()
    
    exprtkObj.SetDoubleVariableValue("x", 8)

    fmt.Println(exprtkObj.GetEvaluatedValue())
}

This package has many capabilities


This package will probably work for your needs: https://github.com/Knetic/govaluate

expression, err := govaluate.NewEvaluableExpression("(x + 2) / 10");

parameters := make(map[string]interface{}, 8)
parameters["x"] = 8;

result, err := expression.Evaluate(parameters);

I have made my own equation evaluator, using Djikstra's Shunting Yard Algorithm. It supports all operators, nested parenthesis, functions and even user defined variables.

It is written in pure go

https://github.com/marcmak/calc


You will probably need to resort to a library that interprets math statements or have to write your own parser. Python being a dynamic language can parse and execute python code at runtime. Standard Go cannot do that.

If you want to write a parser on your own, the go package will be of help. Example (On play):

import (
    "go/ast"
    "go/parser"
    "go/token"
)

func main() {
    fs := token.NewFileSet()
    tr, _ := parser.ParseExpr("(3-1) * 5")
    ast.Print(fs, tr)
}

The resulting AST (Abstract Syntax Tree) can then be traversed and interpreted as you choose (handling '+' tokens as addition for the now stored values, for example).

Tags:

Go