expression

package
v0.0.0-...-0505374 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2024 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package expression provides support for parsing, evaluating and comparing simple mathematical expressions.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AreCompoundsEquivalent

func AreCompoundsEquivalent(e1, e2 Compound, level ComparisonLevel) bool

AreCompoundsEquivalent compares the two objects using mathematical knowledge. Note that objects with different types are never equivalent, so that (2;) != 2 != {2}

See AreExpressionsEquivalent for the meaning of [level].

func AreDisjointsDomains

func AreDisjointsDomains(domains []Domain, vars Vars) error

AreDisjointsDomains returns an error if the given intervals [from, to] are not disjoints. Domains must be valid, as defined by `FunctionExpr.IsValidAsFunction`.

func AreExpressionsEquivalent

func AreExpressionsEquivalent(e1, e2 *Expr, level ComparisonLevel) bool

AreExpressionsEquivalent compares the two expressions using mathematical knowledge, as hinted by `level`. For instance, (a+b)^2 and (a^2 + 2ab + b^2) are equivalent if level == ExpandedSubstitutions, but not with other levels.

func AreFloatEqual

func AreFloatEqual(v1, v2 float64) bool

AreFloatEqual returns `true` if v1 and v2 are equal up to a small threshold, so that floating point rouding errors are ignored

func AreLinearEquationsEquivalent

func AreLinearEquationsEquivalent(e1, e2 Compound) bool

AreLinearEquationsEquivalent returns [true] if both expressions defines the same linear equation (up to a non zero factor).

It always returns false if [e1] or [e2] are not *Expr.

func AreSortedNumbers

func AreSortedNumbers(exprs []*Expr, vars Vars) error

AreSortedNumbers evaluates the expressions using `vars`, checking if all are valid numbers and are sorted (in ascending order)

func IsInt

func IsInt(v float64) (int, bool)

IsInt returns `true` if `v` is a finite integer number.

func RoundFloat

func RoundFloat(v float64) float64

RoundFloat returns `v` rounded to the precision used by `AreFloatEqual`. It should be used to avoid float imprecision when displaying numbers. It used internally when displaying expressions.

Types

type ComparisonLevel

type ComparisonLevel uint8

ComparisonLevel speficies how mathematical expressions should be compared. Depending on the context, it is preferable to ask for exact matching (like when learning distributivity), or to accept broader answers, such as for derivatives.

const (
	// Expressions are compared structurally
	// This is usually too restrictive to be useful
	// For instance, x + 2 != 2 + x according to this level,
	// or 1/4 != 0.25
	Strict ComparisonLevel = iota
	// Expressions are compared after performing some basic transformations,
	// such as reording operands.
	// Also, if both expressions may be evaluated, equal values are considered equal.
	SimpleSubstitutions
	// Apply many subsitutions to get a very robust comparison
	// For instance, multiplications are expanded and equal terms grouped.
	// Operations on numbers are also performed.
	ExpandedSubstitutions
)

func (ComparisonLevel) String

func (l ComparisonLevel) String() string

type Compound

type Compound interface {

	// String returns a human readable form of the expression.
	// The expression is prettified, meaning the structure of the
	// returned expression may slightly differ, but is garanteed
	// to be mathematically equivalent.
	// See `AsLaTeX` for a better display format.
	String() string

	// AsLaTeX returns a valid LaTeX code displaying the expression.
	AsLaTeX() string

	// Substitute replaces variables contained in `vars`, updating the math object in place.
	Substitute(vars Vars)

	// Expressions returns the sub expressions
	Expressions() []*Expr
	// contains filtered or unexported methods
}

Compound is a sum type for a complex math object, built on [Expr]s, such as sets, intervals, or vectors. For compatibility, *Expr are also implementing Compound. Note that nested compound objects, such as sets of sets, are not supported.

func ParseCompound

func ParseCompound(expr string) (out Compound, err error)

ParseCompound accepts an expression describing a complex math object, extending Parse. If invalid, ErrInvalidExpr is returned.

type Domain

type Domain struct {
	From, To *Expr
}

func (Domain) IsIncludedIntoOne

func (d Domain) IsIncludedIntoOne(domains []Domain, vars Vars) error

IsIncludedIntoOne returns an error if [d] is not included in any [domains].

func (Domain) String

func (d Domain) String() string

type ErrCycleVariable

type ErrCycleVariable struct {
	InCycle Variable
}

func (ErrCycleVariable) Error

func (mv ErrCycleVariable) Error() string

type ErrDuplicateParameter

type ErrDuplicateParameter struct {
	Duplicate Variable
}

func (ErrDuplicateParameter) Error

func (err ErrDuplicateParameter) Error() string

type ErrIntrinsic

type ErrIntrinsic string // in french

func (ErrIntrinsic) Error

func (err ErrIntrinsic) Error() string

type ErrInvalidExpr

type ErrInvalidExpr struct {
	Input  string
	Reason string // in french
	Pos    int    // index in the input rune slice
}

ErrInvalidExpr is returned by `Parse` and `ParseCompound`.

func (ErrInvalidExpr) Error

func (inv ErrInvalidExpr) Error() string

func (ErrInvalidExpr) Portion

func (inv ErrInvalidExpr) Portion() string

Portion returns the start of `expr` until the error.

type ErrInvalidRandomParameters

type ErrInvalidRandomParameters struct {
	Detail string
	Cause  Variable
}

ErrInvalidRandomParameters is returned when instantiating invalid parameter definitions

func (ErrInvalidRandomParameters) Error

func (irv ErrInvalidRandomParameters) Error() string

type ErrMissingVariable

type ErrMissingVariable struct {
	Missing Variable
}

func (ErrMissingVariable) Error

func (mv ErrMissingVariable) Error() string

type Expr

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

Expr is a parsed mathematical expression

func MustParse

func MustParse(s string) *Expr

MustParse is the same as Parse but panics on invalid expressions.

func NewNb

func NewNb(v float64) *Expr

NewNb returns the one element expression containing the given number. For consistency with the parser, negative numbers are actually returned as -(...)

func NewVarExpr

func NewVarExpr(v Variable) *Expr

NewVarExpr is a convenience constructor converting a `Variable` to an expression.

func Parse

func Parse(s string) (*Expr, error)

Parse parses a mathematical expression. If invalid, an `ErrInvalidExpr` is returned.

func (*Expr) AsLaTeX

func (expr *Expr) AsLaTeX() string

AsLaTeX returns a valid LaTeX code displaying the expression.

func (*Expr) Copy

func (expr *Expr) Copy() *Expr

Copy returns a deep copy of the expression.

func (*Expr) DefaultSimplify

func (expr *Expr) DefaultSimplify()

DefaultSimplify performs a serie of basic simplifications, removing zero values and -(-...). It is used before printing an expression, and should also be used after substitutions. Note that it applies a subset of the simplifications defined by the [SimpleSimplifications] flag.

func (*Expr) Evaluate

func (expr *Expr) Evaluate(vars Vars) (float64, error)

Evaluate uses the given variables values to evaluate the formula. If a variable is referenced in the expression but not in the bindings, `ErrMissingVariable` is returned. If a variable is in a cycle and can't be resolved, ErrCycleVariable` is returned. If the expression is not valid, like in randInt(2; -2), `ErrInvalidExpr` is returned

func (*Expr) Expressions

func (e *Expr) Expressions() []*Expr

func (*Expr) IsFraction

func (expr *Expr) IsFraction() bool

IsFraction returns true for expression of the form (...) / (...)

func (*Expr) IsIncludedIntoOne

func (expr *Expr) IsIncludedIntoOne(domains []Domain, vars Vars) error

IsIncludedIntoOne returns an error if [expr], after evaluation does not belong to one of [domains].

func (*Expr) IsValidIndex

func (expr *Expr) IsValidIndex(vars Vars, length int) error

IsValidIndex evaluates the expression using `vars`, then checks if it is usable as input in a slice of length `length`. Note that we adopt the mathematical convention, with indices starting at 1. Thus the result is valid if it is an integer in [1, length]

func (*Expr) IsValidLinearEquation

func (expr *Expr) IsValidLinearEquation(vars Vars) error

IsValidLinearEquation checks that, once instantiated, [expr] is a linear equation (such as 2x - 3y + t/2 - 0.5)

func (*Expr) IsValidNumber

func (expr *Expr) IsValidNumber(vars Vars, checkPrecision, rejectInfinite bool) error

IsValidNumber evaluates the expression using `vars`, checking if it is a valid number. If `checkPrecision` is true, it also checks that the number is not exceeding the float precision used in `AreFloatEqual`. If `rejectInfinite` is true, it returns an error for +/-Inf

func (*Expr) IsValidProba

func (expr *Expr) IsValidProba(vars Vars) error

IsValidProba is the same as IsValidNumber, but also checks the number is in [0;1]

func (*Expr) Serialize

func (expr *Expr) Serialize() string

Serialize returns the expression as text. It is meant to be used for internal exchange; see String() and AsLaTex() for display.

func (*Expr) String

func (expr *Expr) String() string

String returns a human readable form of the expression. The expression is prettified, meaning the structure of the returned expression may slightly differ, but is garanteed to be mathematically equivalent. See `AsLaTeX` for a better display format.

func (*Expr) Substitute

func (expr *Expr) Substitute(vars Vars)

Substitute replaces variables contained in `vars`, updating `expr` in place.

func (*Expr) SyntaxHints

func (e *Expr) SyntaxHints() SyntaxHints

SyntaxHints returns a set of hints needed to type [e]

func (*Expr) ToBinarySet

func (expr *Expr) ToBinarySet() (sets.BinarySet, error)

ToBinarySet interprets [expr] as a set expression

type FunctionDefinition

type FunctionDefinition struct {
	FunctionExpr         // instantiated version
	From, To     float64 // definition domain, with From <= To
}

FunctionDefinition interprets an expression as mathematical function, where random parameters have been resolved

type FunctionExpr

type FunctionExpr struct {
	Function *Expr
	Variable Variable // usually x
}

func (FunctionExpr) Closure

func (f FunctionExpr) Closure() func(float64) float64

Closure returns a function computing f(x), where f is defined by the expression. The closure will silently return NaN if the expression is invalid.

func (FunctionExpr) IsValidAsFunction

func (fn FunctionExpr) IsValidAsFunction(domain Domain, vars Vars, bound float64) error

IsValidAsFunction evaluates the function expression using `vars`, and checks if the (estimated) extrema of |f| is less than `bound`, returning an error if not.

func (FunctionExpr) IsValidAsSequence

func (fn FunctionExpr) IsValidAsSequence(domain Domain, vars Vars, bound float64) error

IsValidAsSequence evaluates the sequence expression using `vars`, and checks if the (estimated) extrema of |f| is less than `bound`, returning an error if not.

type Instantiater

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

func NewInstantiater

func NewInstantiater(rv RandomParameters) *Instantiater

func (*Instantiater) Instantiate

func (inst *Instantiater) Instantiate() (Vars, error)

func (*Instantiater) Reset

func (inst *Instantiater) Reset()

type Interval

type Interval struct {
	Left, Right *Expr
	// Open means reject the boundary
	LeftOpen, RightOpen bool
}

Interval is a math interval (range) such as [2;4]

func (Interval) AsLaTeX

func (inter Interval) AsLaTeX() string

func (Interval) Expressions

func (inter Interval) Expressions() []*Expr

func (Interval) String

func (inter Interval) String() string

func (Interval) Substitute

func (inter Interval) Substitute(vars Vars)

type Number

type Number float64

func (Number) String

func (v Number) String() string

type RandomParameters

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

RandomParameters stores a set of random parameters definitions, which may be related, but cannot contain cycles.

func NewRandomParameters

func NewRandomParameters() *RandomParameters

func (RandomParameters) DefinedVariables

func (rp RandomParameters) DefinedVariables() []Variable

func (RandomParameters) Instantiate

func (rv RandomParameters) Instantiate() (Vars, error)

Instantiate generates a random version of the variables, resolving possible dependencies.

The general idea is to replace known variables by their expression (recursively) and to perform a partial evaluation. The selectors involved in random generators are evaluated, and the resulting expression are evaluated if valid. However, free variables are accepted, so that the result may be a plain number, but also a symbol, or even a mix of expression.

It returns an `ErrInvalidRandomParameters` error for invalid cycles, like a = a + 1 or a = b + 1; b = a.

See `Validate` to statistically check for invalid parameters.

func (RandomParameters) IsDefined

func (rp RandomParameters) IsDefined(v Variable) bool

IsDefined returns true if the variable [v] is defined (regular variables and special functions included)

func (*RandomParameters) ParseIntrinsic

func (rd *RandomParameters) ParseIntrinsic(s string) error

ParseIntrinsic interprets `s` as a special function definition, adding it to the parameters. It returns `ErrIntrinsic` is the definition is invalid.

func (RandomParameters) ParseVariable

func (rp RandomParameters) ParseVariable(v Variable, expr string) error

ParseVariable parses the given expression and adds it to the parameters

func (RandomParameters) Validate

func (rv RandomParameters) Validate() error

Validate calls `Instantiate` many times to make sure the parameters are always valid regardless of the random value chosen. If not, it returns the first error encountered.

type Set

type Set []*Expr

Set is a set of expression, such as {1; x^2; x^4}

func (Set) AsLaTeX

func (set Set) AsLaTeX() string

func (Set) Expressions

func (set Set) Expressions() []*Expr

func (Set) String

func (set Set) String() string

func (Set) Substitute

func (set Set) Substitute(vars Vars)

type SyntaxHint

type SyntaxHint uint8

SyntaxHint refers to a hint for a peculiar expression, among :

inf : \infty s'écrit inf
-inf: -\infty s'écrit -inf
a/b (simple): \frac{3}{5} s'écrit 3 / 5
a/b (complex): \frac{2x+1}{-3x+7} s'écrit (2x + 1) / (-3x + 7)
x^n (n >= 2) : x^2 s'écrit x^2
sqrt(3) : \sqrt{3} s'écrit sqrt(3)

type SyntaxHints

type SyntaxHints map[SyntaxHint]bool

SyntaxHints is a set of SyntaxHint

func (SyntaxHints) Append

func (sh SyntaxHints) Append(other SyntaxHints)

Append add [other] to the set

func (SyntaxHints) Text

func (sh SyntaxHints) Text() string

Text returns a french string using interpolation syntax $ $ for LaTeX

type Variable

type Variable struct {
	Indice string // optional
	Name   rune
}

Variable is a (one letter) mathematical variable, such as 'a', 'b' in (a + b)^2 or 'x' in 2x + 3. Indices are also permitted, written in LaTeX format : x_A or x_AB Variable is also used to store a custom symbol.

func NewVar

func NewVar(x rune) Variable

NewVar is a convenience constructor for a simple variable.

func NewVarI

func NewVarI(x rune, indice string) Variable

NewVarI is a convenience constructor supporting indices.

func (Variable) String

func (v Variable) String() string

type Vars

type Vars map[Variable]*Expr

Vars maps variables to a chosen value.

func (Vars) CompleteFrom

func (vs Vars) CompleteFrom(other Vars)

CompleteFrom adds entries in [other] not defined in [vs]

type Vector

type Vector []*Expr

Vector is a n-uplet of expressions, such as (1;2;3;4;5)

func (Vector) AsLaTeX

func (vec Vector) AsLaTeX() string

func (Vector) Expressions

func (vec Vector) Expressions() []*Expr

func (Vector) String

func (vec Vector) String() string

func (Vector) Substitute

func (vec Vector) Substitute(vars Vars)

Directories

Path Synopsis
Package sets implement basic math sets theory, usefull to evaluate an answer.
Package sets implement basic math sets theory, usefull to evaluate an answer.

Jump to

Keyboard shortcuts

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