Skip to content

Repository files navigation

ThinkSharp.FormulaParser

Build statusNuGetLicenseDonate

Introduction

ThinkSharp.FormulaParser is a simple library with fluent API for parsing and evaluating mathematical formulas.

Mathematical formulas can be parsed to a parsing tree (hereinafter called "parsing") or directly evaluated to a numeric value (hereinafter called "evaluating").

The following features are supported

  • Basic mathematical operations: +, -, /, *, ^, ( .. ), scientific notation (3e2 = 300)
  • Variables: Detect variables on parsing or use a dictionary to provide variables for evaluation.
  • Constants: Use build-in constants (pi, e) or define your own. Constants are available independent of the provided variables.
  • Functions: Use build-in functions (sqrt, sum, rnd, abs, log, ln, sin, cos, tan, min, max) or define your own.
  • Error Handling: The parser provides an expressive error message in case of invalid formulas.
  • Customization: The parser may be configured to disable features and add custom functions / constants.

Installation

ThinkSharp.FormulaParser can be installed via Nuget

 Install-Package ThinkSharp.FormulaParser

Examples

Evaluating formulas

// The simples way to create a formula parser is the static method 'Create'. varparser=FormulaParser.Create();// Parsing a simple mathematical formulavarresult1=parser.Evaluate("1+1").Value;// result1 = 2.0// Usage of variablesvarvariables=newDictionary<string,double>{["x"]=2.0};varresult2=parser.Evaluate("1+x",variables).Value;// result2 = 3.0// Usage of functionsvarresult3=parser.Evaluate("1+min(3,4)").Value;// result3 = 4.0// Handle errorsvarparsingResult=parser.Evaluate("2*?");if(!parsingResult.Success){Console.WriteLine(parsingResult.Error);// "column 2: token recognition error at: '?'"}

Creating and evaluating a parsing tree

varparser=FormulaParser.Create();varvariables=newDictionary<string,double>{["x"]=2.0};// Parsing a simple mathematical formulavarnode1=parser.Parse("1+x",variables).Value;// |FormulaNode("1+x")// |- Child: BinaryOperatorNode(+)// |- LeftNode: NumericNode(1.0)// |- RightNode: VariableNode("x")varresult1=parser.Evaluate(node1,variables).Value;// result = 3.0varnode2=parser.Parse("pi * sqrt(3*x)",variables).Value;// |FormulaNode("pi * sqrt(3*x)")// |- Child: BinaryOperatorNode(*)// |- LeftNode: ConstantNode("pi")// |- RightNode: FunctionNode("sqrt")// |- Parameters: [BinaryOperationNode(*)]// |- LeftNode: Numeric(3.0)// |- RightNode: VariableNode("x") varresult2=parser.Evaluate(node2,variables).Value;// result = 7.695...

Configure custom functions / constants

varparser=FormulaParser.CreateBuilder().ConfigureConstats(constants =>{// constants.RemoveAll() for removing all default constants// constants.Remove("pi") for removing constants by nameconstants.Add("h",6.62607015e-34);}).ConfigureFunctions(functions =>{// functions.RemoveAll() for removing all default functions// functions.Remove("sum") for removing function by name// define functions with certain number of parameters (1-5 parameters are supported)functions.Add("celsiusToFarenheit", celsius =>celsius*1.8+32);functions.Add("fahrenheitToCelsius", fahrenheit =>(fahrenheit-32)*5/9);functions.Add("p1_plus_p2_plus_p3",(p1,p2,p3)=>p1+p2+p3);// define function with 2 to n number of parameters (typeof(nums) = double[])functions.Add("product", nums =>nums.Aggregate((p1,p2)=>p1*p2));}).Build();varpoolTemperatureInCelsius=parser.Evaluate("celsiusToFarenheit(fahrenheitToCelsius(30))").Value;// poolTemperatureInCelsius = 30varresult2=parser.Evaluate("product(2, 2, 2, 2, 2, 2)").Value;// result2 = 2^6 = 128varresult3=parser.Evaluate("p1_plus_p2_plus_p3(1, 2, 3)").Value;// result3 = 6stringerror1=parser.Evaluate("celsiusToFarenheit(1, 2)").Error;// column 0: There is no function 'celsiusToFarenheit' that takes 2 argument(s).stringerror2=parser.Evaluate("product()").Error;// column 0: There is no function 'product' that takes 0 argument(s).stringerror3=parser.Evaluate("p1_plus_p2_plus_p3(1, 2)").Error;// column 0: There is no function 'p1_plus_p2_plus_p3' that takes 2 argument(s).

License

ThinkSharp.FormulaParser is released under The MIT license (MIT)

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Donation

If you like ThinkSharp.FormulaParser and use it in your project(s), feel free to give me a cup of coffee :)

paypal

About

A customizable formula parser with fluent API that allows parsing and evaluation of mathematically formulas.

Topics

Resources

Stars

5 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages