Skip to content

Latest commit

 

History

History
269 lines (205 loc) · 5.61 KB

File metadata and controls

269 lines (205 loc) · 5.61 KB

Quick Reference Guide

Installation

go get github.com/BaseMax/go-math-opt

Import

import "github.com/BaseMax/go-math-opt"

Basic Usage

Parse an Expression

expr, err := mathopt.Parse("x ^ 2 + 2 * x + 1")
if err != nil {
    log.Fatal(err)
}

Evaluate an Expression

result, err := expr.Eval(map[string]float64{"x": 5})
// result = 36

Simplify an Expression

simplified := expr.Simplify()
fmt.Println(simplified.String())

Differentiate an Expression

derivative := expr.Diff("x")
fmt.Println(derivative.Simplify().String())
// Output: 2 * x + 2

Check Equivalence

e1, _ := mathopt.Parse("x + 0")
e2, _ := mathopt.Parse("x")
equal := mathopt.ExpressionEquivalence(e1, e2)
// equal = true

Constant Folding

expr, _ := mathopt.Parse("(2 + 3) * (4 + 1)")
folded := mathopt.ConstantFold(expr)
fmt.Println(folded.String())
// Output: 25

Supported Syntax

Numbers

  • Integers: 42, 0, -5
  • Decimals: 3.14, 0.5, -2.718

Variables

  • Single letters: x, y, z
  • Multi-character: theta, alpha, var1

Binary Operators

Operator Description Example
+ Addition x + 5
- Subtraction x - 3
* Multiplication 2 * x
/ Division x / 2
^ Exponentiation x ^ 2

Unary Operators

Operator Description Example
- Negation -x
sin() Sine sin(x)
cos() Cosine cos(x)
exp() Exponential exp(x)
ln() Natural log ln(x)

Parentheses

Use parentheses to group operations: (x + 1) * (x - 1)

Operator Precedence

  1. Highest: Parentheses ()
  2. Functions: sin(), cos(), etc.
  3. Exponentiation: ^
  4. Multiplication/Division: *, /
  5. Lowest: Addition/Subtraction: +, -

Common Patterns

Polynomial Differentiation

// f(x) = x^3 + 2x^2 + x + 1
expr, _ := mathopt.Parse("x ^ 3 + 2 * x ^ 2 + x + 1")
derivative := expr.Diff("x").Simplify()
// f'(x) = 3x^2 + 4x + 1

Chain Rule

// f(x) = sin(x^2)
expr, _ := mathopt.Parse("sin(x ^ 2)")
derivative := expr.Diff("x").Simplify()
// f'(x) = cos(x^2) * 2x

Product Rule

// f(x) = x * sin(x)
expr, _ := mathopt.Parse("x * sin(x)")
derivative := expr.Diff("x").Simplify()
// f'(x) = sin(x) + x*cos(x)

Quotient Rule

// f(x) = x / (x + 1)
expr, _ := mathopt.Parse("x / (x + 1)")
derivative := expr.Diff("x").Simplify()
// f'(x) = 1 / (x + 1)^2

Multi-Variable Expressions

expr, _ := mathopt.Parse("x * y + z")

// Partial derivative with respect to x
dfdx := expr.Diff("x").Simplify() // y

// Partial derivative with respect to y
dfdy := expr.Diff("y").Simplify() // x

// Partial derivative with respect to z
dfdz := expr.Diff("z").Simplify() // 1

Expression Interface Methods

String() string

Returns a human-readable string representation.

expr, _ := mathopt.Parse("x + 5")
fmt.Println(expr.String()) // "x + 5"

Eval(vars map[string]float64) (float64, error)

Evaluates the expression numerically with given variable values.

expr, _ := mathopt.Parse("x ^ 2 + 1")
result, err := expr.Eval(map[string]float64{"x": 3})
// result = 10

Diff(variable string) Expr

Computes the symbolic derivative with respect to a variable.

expr, _ := mathopt.Parse("x ^ 2")
derivative := expr.Diff("x") // 2 * x

Simplify() Expr

Simplifies the expression using algebraic rules.

expr, _ := mathopt.Parse("1 * x + 0")
simplified := expr.Simplify() // x

Equals(other Expr) bool

Checks if two expressions are structurally identical.

e1, _ := mathopt.Parse("x + 1")
e2, _ := mathopt.Parse("x + 1")
equal := e1.Equals(e2) // true

Error Handling

Parse Errors

expr, err := mathopt.Parse("x +")
if err != nil {
    fmt.Println("Parse error:", err)
    // Parse error: unexpected end of expression
}

Evaluation Errors

expr, _ := mathopt.Parse("x + y")
result, err := expr.Eval(map[string]float64{"x": 5})
if err != nil {
    fmt.Println("Eval error:", err)
    // Eval error: undefined variable: y
}

Division by Zero

expr, _ := mathopt.Parse("1 / 0")
result, err := expr.Eval(nil)
if err != nil {
    fmt.Println("Math error:", err)
    // Math error: division by zero
}

Tips and Best practices

  1. Always check errors from Parse() and Eval()
  2. Simplify after differentiation for cleaner results
  3. Use MustParse() only in tests where panic is acceptable
  4. Variables are case-sensitive: xX
  5. Spaces are optional but improve readability
  6. Constant fold early to optimize performance
  7. Cache parsed expressions if used repeatedly

Examples

See the examples/demo.go file for comprehensive usage examples.

Common Issues

Expression not simplified as expected

The simplifier has limited capabilities. For advanced simplification:

  • Apply multiple simplification passes
  • Manually restructure the expression
  • Consider implementing custom simplification rules

Differentiation produces complex results

This is expected for complex expressions. The result is mathematically correct but may need manual simplification.

Performance concerns

For high-performance scenarios:

  • Cache parsed expressions
  • Pre-simplify constant parts
  • Consider expression compilation to Go functions

Links