Documentation
¶
Overview ¶
Package expression provides support for parsing, evaluating and comparing simple mathematical expressions.
Index ¶
- func AreCompoundsEquivalent(e1, e2 Compound, level ComparisonLevel) bool
- func AreDisjointsDomains(domains []Domain, vars Vars) error
- func AreExpressionsEquivalent(e1, e2 *Expr, level ComparisonLevel) bool
- func AreFloatEqual(v1, v2 float64) bool
- func AreLinearEquationsEquivalent(e1, e2 Compound) bool
- func AreSortedNumbers(exprs []*Expr, vars Vars) error
- func IsInt(v float64) (int, bool)
- func RoundFloat(v float64) float64
- type ComparisonLevel
- type Compound
- type Domain
- type ErrCycleVariable
- type ErrDuplicateParameter
- type ErrIntrinsic
- type ErrInvalidExpr
- type ErrInvalidRandomParameters
- type ErrMissingVariable
- type Expr
- func (expr *Expr) AsLaTeX() string
- func (expr *Expr) Copy() *Expr
- func (expr *Expr) DefaultSimplify()
- func (expr *Expr) Evaluate(vars Vars) (float64, error)
- func (e *Expr) Expressions() []*Expr
- func (expr *Expr) IsFraction() bool
- func (expr *Expr) IsIncludedIntoOne(domains []Domain, vars Vars) error
- func (expr *Expr) IsValidIndex(vars Vars, length int) error
- func (expr *Expr) IsValidLinearEquation(vars Vars) error
- func (expr *Expr) IsValidNumber(vars Vars, checkPrecision, rejectInfinite bool) error
- func (expr *Expr) IsValidProba(vars Vars) error
- func (expr *Expr) Serialize() string
- func (expr *Expr) String() string
- func (expr *Expr) Substitute(vars Vars)
- func (e *Expr) SyntaxHints() SyntaxHints
- func (expr *Expr) ToBinarySet() (sets.BinarySet, error)
- type FunctionDefinition
- type FunctionExpr
- type Instantiater
- type Interval
- type Number
- type RandomParameters
- func (rp RandomParameters) DefinedVariables() []Variable
- func (rv RandomParameters) Instantiate() (Vars, error)
- func (rp RandomParameters) IsDefined(v Variable) bool
- func (rd *RandomParameters) ParseIntrinsic(s string) error
- func (rp RandomParameters) ParseVariable(v Variable, expr string) error
- func (rv RandomParameters) Validate() error
- type Set
- type SyntaxHint
- type SyntaxHints
- type Variable
- type Vars
- type Vector
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 ¶
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 ¶
AreFloatEqual returns `true` if v1 and v2 are equal up to a small threshold, so that floating point rouding errors are ignored
func AreLinearEquationsEquivalent ¶
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 ¶
AreSortedNumbers evaluates the expressions using `vars`, checking if all are valid numbers and are sorted (in ascending order)
func RoundFloat ¶
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 ¶
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 ¶
IsIncludedIntoOne returns an error if [d] is not included in any [domains].
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 ¶
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 NewNb ¶
NewNb returns the one element expression containing the given number. For consistency with the parser, negative numbers are actually returned as -(...)
func NewVarExpr ¶
NewVarExpr is a convenience constructor converting a `Variable` to an 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 ¶
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 (*Expr) IsFraction ¶
IsFraction returns true for expression of the form (...) / (...)
func (*Expr) IsIncludedIntoOne ¶
IsIncludedIntoOne returns an error if [expr], after evaluation does not belong to one of [domains].
func (*Expr) IsValidIndex ¶
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 ¶
IsValidLinearEquation checks that, once instantiated, [expr] is a linear equation (such as 2x - 3y + t/2 - 0.5)
func (*Expr) IsValidNumber ¶
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 ¶
IsValidProba is the same as IsValidNumber, but also checks the number is in [0;1]
func (*Expr) Serialize ¶
Serialize returns the expression as text. It is meant to be used for internal exchange; see String() and AsLaTex() for display.
func (*Expr) 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 ¶
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]
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 ¶
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) Expressions ¶
func (Interval) Substitute ¶
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) Expressions ¶
func (Set) Substitute ¶
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 ¶
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.
type Vars ¶
Vars maps variables to a chosen value.
func (Vars) CompleteFrom ¶
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) Expressions ¶
func (Vector) Substitute ¶
Source Files
¶
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. |