formulae

package module
v0.0.0-...-015c70e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 26, 2020 License: MIT Imports: 10 Imported by: 1

README

Formulae Build Status GoDoc

Online demo if you need to draw formulae now.


Formulae is a formula parser and calculator and can optimize and derive (to x) formulae.

From

sin(cos(x))^2+1/x-1

To

example.png

Installation

Run the following command

go get github.com/tdewolff/formulae

or add the following import and run the project with go get

import (
	"github.com/tdewolff/formulae"
)

Usage

Parse

Parse a formula from string and return a Function.

f := formulae.Parse("sin(cos(x))^2+1/x-1")
Calculate

Calculate the function for a single x value.

y, err := f.Calc(5+0i) // -0.722...
if err != nil {
    panic(err)
}
Interval

Calculate the function between the interval a and b, with step-size step.

ys, errs := f.Interval(a, step, b)
if len(errs) != 0 {
    panic("errors")
}
Optimize

Optimize the function by elimination and simplification.

f.Optimize()
Derive to x

Obtain the derivative of f to x.

df := f.Derivative()
LaTeX notation

Export as LaTeX notation

s := f.LaTeX() // $$f(x) = \sin(\cos(x))^{2}+\frac{1}{x}-1$$

Example

Basic example that plots to image.

package main

import (
	"fmt"
	"image/color"
	"log"
	"os"

	"github.com/tdewolff/formulae"
	"gonum.org/v1/plot"
	"gonum.org/v1/plot/plotter"
	"gonum.org/v1/plot/vg"
)

func main() {
	// Parse formula
	in := "sin(cos(x))^2+1/x-1"
	f, errs := formulae.Parse(in)
	if len(errs) > 0 {
		log.Fatal(errs)
	}
	df := f.Derivative()

	// Calculate function
	xs, ys, errs := f.Interval(0.5, 0.01, 5.0)
	if len(errs) > 0 {
		log.Fatal(errs)
	}
	xys := make(plotter.XYs, len(xs))
	for i := range xs {
		xys[i].X = xs[i]
		xys[i].Y = real(ys[i])
	}
	_, _, ymin, _ := plotter.XYRange(xys)
	if ymin > 0 {
		ymin = 0
	}

	// Calculate function derivative
	xs2, ys2, errs := df.Interval(0.5, 0.01, 5.0)
	if len(errs) > 0 {
		log.Fatal(errs)
	}
	xys2 := make(plotter.XYs, len(xs2))
	for i := range xs2 {
		xys2[i].X = xs2[i]
		xys2[i].Y = real(ys2[i])
	}

	// Plot functions
	p, err := plot.New()
	if err != nil {
		log.Fatal(err)
	}

	p.Title.Text = "Formula"
	p.X.Label.Text = "x"
	p.Y.Label.Text = "y"
	p.Y.Min = ymin

	line, err := plotter.NewLine(xys)
	if err != nil {
		log.Fatal(err)
	}
	line2, err := plotter.NewLine(xys2)
	if err != nil {
		log.Fatal(err)
	}
	line2.LineStyle.Color = color.Gray{192}

	p.Add(plotter.NewGrid())
	p.Add(line)
	p.Add(line2)
	p.Legend.Add("f", line)
	p.Legend.Add("df/dx", line2)

	if err := p.Save(8*vg.Inch, 4*vg.Inch, "formula.png"); err != nil {
		log.Fatal(err)
	}
}

License

Released under the MIT license.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultVars = Vars{
	"e":   complex(math.E, 0),
	"pi":  complex(math.Pi, 0),
	"phi": complex(math.Phi, 0),
}
View Source
var ErrNoOperand = fmt.Errorf("no operand")
View Source
var MinusOneNode = &Number{val: -1 + 0i}
View Source
var OneNode = &Number{val: 1 + 0i}
View Source
var OpPrec = map[Operator]int{
	FuncOp:     1,
	MultiplyOp: 2,
	DivideOp:   2,
	PowerOp:    3,
	MinusOp:    4,
}
View Source
var OpRightAssoc = map[Operator]bool{
	PowerOp: true,
	MinusOp: true,
	FuncOp:  true,
}
View Source
var TwoNode = &Number{val: 2 + 0i}
View Source
var ZeroNode = &Number{val: 0 + 0i}

Functions

This section is empty.

Types

type Expr

type Expr struct {
	// contains filtered or unexported fields
}

func (*Expr) Calc

func (n *Expr) Calc(x complex128, vars Vars) (complex128, error)

func (*Expr) Derivative

func (n *Expr) Derivative() Node

func (*Expr) Equal

func (n *Expr) Equal(iother Node) bool

func (*Expr) LaTeX

func (n *Expr) LaTeX() string

func (*Expr) String

func (n *Expr) String() string

type Func

type Func struct {
	// contains filtered or unexported fields
}

func (*Func) Calc

func (n *Func) Calc(x complex128, vars Vars) (complex128, error)

func (*Func) Derivative

func (n *Func) Derivative() Node

func (*Func) Equal

func (n *Func) Equal(iother Node) bool

func (*Func) LaTeX

func (n *Func) LaTeX() string

func (*Func) String

func (n *Func) String() string

type Function

type Function struct {
	Vars
	// contains filtered or unexported fields
}

func Parse

func Parse(in string) (*Function, []error)

func (*Function) Calc

func (f *Function) Calc(x complex128) (complex128, error)

func (*Function) Derivative

func (f *Function) Derivative() *Function

func (*Function) Interval

func (f *Function) Interval(xMin, xStep, xMax float64) ([]float64, []complex128, []error)

func (*Function) LaTeX

func (f *Function) LaTeX() string

func (*Function) Optimize

func (f *Function) Optimize()

func (*Function) String

func (f *Function) String() string

type Lexer

type Lexer struct {
	// contains filtered or unexported fields
}

Lexer is the state for the lexer.

func NewLexer

func NewLexer(r io.Reader) *Lexer

NewLexer returns a new Lexer for a given io.Reader.

func (*Lexer) Err

func (l *Lexer) Err() error

Err returns the error encountered during lexing, this is often io.EOF but also other errors can be returned.

func (*Lexer) Function

func (l *Lexer) Function() hash.Hash

func (*Lexer) Next

func (l *Lexer) Next() (TokenType, []byte)

Next returns the next Token. It returns ErrorToken when an error was encountered. Using Err() one can retrieve the error message.

func (*Lexer) Operator

func (l *Lexer) Operator() Operator

func (*Lexer) Pos

func (l *Lexer) Pos() int

func (*Lexer) Restore

func (l *Lexer) Restore()

Restore restores the NULL byte at the end of the buffer.

type Node

type Node interface {
	String() string
	LaTeX() string
	Equal(Node) bool
	Derivative() Node
	Calc(complex128, Vars) (complex128, error)
}

func Optimize

func Optimize(in Node) Node

type Number

type Number struct {
	// contains filtered or unexported fields
}

func (*Number) Calc

func (n *Number) Calc(x complex128, vars Vars) (complex128, error)

func (*Number) Derivative

func (n *Number) Derivative() Node

func (*Number) Equal

func (n *Number) Equal(iother Node) bool

func (*Number) LaTeX

func (n *Number) LaTeX() string

func (*Number) String

func (n *Number) String() string

type Operator

type Operator int
const (
	UnknownOp Operator = iota
	FuncOp
	OpenOp
	CloseOp
	AddOp
	SubtractOp
	MinusOp
	MultiplyOp
	DivideOp
	PowerOp
)

func (Operator) String

func (op Operator) String() string

type ParseError

type ParseError struct {
	// contains filtered or unexported fields
}

func ParseErrorf

func ParseErrorf(pos int, format string, args ...interface{}) ParseError

func (ParseError) Error

func (pe ParseError) Error() string

func (ParseError) Pos

func (pe ParseError) Pos() int

type Parser

type Parser struct {
	// contains filtered or unexported fields
}

type SYToken

type SYToken struct {
	// contains filtered or unexported fields
}

func (SYToken) String

func (t SYToken) String() string

type TokenType

type TokenType uint32

TokenType determines the type of token, eg. a number or a semicolon.

const (
	ErrorToken TokenType = iota // extra token when errors occur
	UnknownToken
	WhitespaceToken // space \t \v \f \r \n
	NumericToken
	IdentifierToken
	OperatorToken
)

TokenType values.

func (TokenType) String

func (tt TokenType) String() string

String returns the string representation of a TokenType.

type UnaryExpr

type UnaryExpr struct {
	// contains filtered or unexported fields
}

func (*UnaryExpr) Calc

func (n *UnaryExpr) Calc(x complex128, vars Vars) (complex128, error)

func (*UnaryExpr) Derivative

func (n *UnaryExpr) Derivative() Node

func (*UnaryExpr) Equal

func (n *UnaryExpr) Equal(iother Node) bool

func (*UnaryExpr) LaTeX

func (n *UnaryExpr) LaTeX() string

func (*UnaryExpr) String

func (n *UnaryExpr) String() string

type Variable

type Variable struct {
	// contains filtered or unexported fields
}

func (*Variable) Calc

func (n *Variable) Calc(x complex128, vars Vars) (complex128, error)

func (*Variable) Derivative

func (n *Variable) Derivative() Node

func (*Variable) Equal

func (n *Variable) Equal(iother Node) bool

func (*Variable) LaTeX

func (n *Variable) LaTeX() string

func (*Variable) String

func (n *Variable) String() string

type Vars

type Vars map[string]complex128

func (Vars) Duplicate

func (v Vars) Duplicate() Vars

func (Vars) Set

func (v Vars) Set(name string, value complex128)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL