Giter Site home page Giter Site logo

miroiu / string-math Goto Github PK

View Code? Open in Web Editor NEW
41.0 1.0 4.0 229 KB

Evaluates a math expression from a string. Supports variables and custom operators.

License: MIT License

C# 100.00%
expression-evaluator expression-parser csharp dotnet string calculator math mathematics string-math string-calculator

string-math's Introduction

V3 README can be found here: https://github.com/miroiu/string-math/tree/release-3.0.0

NEW! Boolean math example: https://github.com/miroiu/string-math/pull/6/files

String Math NuGet Downloads .NET

Calculates the value of a math expression from a string returning a double. Supports variables, user defined operators and expression compilation.

double result = "1 * (2 - 3) ^ 2".Eval(); // 1

Variables

double result = "{a} + 2 * {b}".Substitute("a", 2).Substitute("b", 3).Result; // 8

Global variables

These variables are inherited and cannot be substituted.

MathExpr.AddVariable("PI", 3.1415926535897931);
double result = "1 + {PI}".Eval(); // 4.1415926535897931

Custom operators

Global operators

These operators are inherited and can be overidden.

MathExpr.AddOperator("abs", a => a > 0 ? a : -a);
double result = "abs -5".Eval(); // 5

// Operator precedence (you can specify an int for precedence)
MathExpr.AddOperator("max", (a, b) => a > b ? a : b, Precedence.Power);
double result = new MathExpr("2 * 3 max 4").Result; // 8

Local operators

These are applied only to the target expression.

MathExpr expr = "{PI} + 1";
expr.SetOperator("+", (a, b) => Math.Pow(a, b));
double result = expr; // 3.1415926535897931

double result2 = "{PI} + 1".Eval(); // 4.1415926535897931

Advanced

Extract variables

var expr = "{a} + {b} + {PI}".ToMathExpr();
var variables = expr.Variables; // { "a", "b", "PI" }
var localVariables = expr.LocalVariables; // { "a", "b" }

Compilation

Func<double, double> fn = "{a} + 2".ToMathExpr().Compile("a");
double result = fn(5); // 7

Conditional substitution

MathExpr expr = "1 / {a}".Substitute("a", 1);

double temp = expr.Result; // 1

if (someCondition)  // true
 expr.Substitute("a", 2);

double final = expr.Result; // 0.5

Sharing math context

MathExpr expr = "{PI} + 1";
expr.SetOperator("+", (a, b) => Math.Pow(a, b));

MathExpr expr2 = "3 + 2".ToMathExpr(expr.Context);

double result = "1 + 2 + 3".Eval(expr.Context);

Custom math context

var context = new MathContext(); // new MathContext(MathContext.Default); // to inherit from global
context.RegisterBinary("+", (a, b) => Math.Pow(a, b));

MathExpr expr = new MathExpr("{PI} + 1", context);
MathExpr expr2 = "3 + 2".ToMathExpr(context);
double result = "1 + 2 + 3".Eval(context);

Default operators

Binary

+ (addition)
- (subtraction)
* (multiplication)
/ (division)
% (remainder)
^ (power)
log (logarithm)
max (maximum)
min (minimum)

Unary

- (negation)
! (factorial)
sqrt (square root)
sin (sine)
asin (arcsine)
cos (cosine)
acos (arccosine)
tan (tangent)
atan (arctangent)
rad (convert degrees to radians)
deg (convert radians to degrees)
ceil (ceiling)
floor (floor)
round (rounding)
exp (e raised to power)
abs (absolute)

string-math's People

Contributors

miroiu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

string-math's Issues

Expression compilation refering to PI global variable.

Based on one of the examples:

        var try1 = "{a} + 2 + {PI}".ToMathExpr();
        var res1 = try1.Substitute("a", 5).Result;

This evaluates as expected, evidently PI exists as a global variable. Trying to compile this to a function doesn't go so well:

        Func<double, double> fn = "{a} + 2 + {PI}".ToMathExpr().Compile("a");
        double result = fn(5); // 7 + PI

This throws an exception at the Compile stage with "Variable 'PI' does not exist.".

Should this work, or am I missing something? Sorry, new to StringMath, trying to get to grips.

Building with 4.1.1.

Thanks!

Duncan

Question about conditionals.

Hi Emanuel-

Looking at how to handle conditionals, as not everything maps to linear functions. I'd really like a fn (a,b,c) which returns b if a else c, or functionality equivalent to a ? b : c

I don't see anything supporting that in the framework. Lunchtime hacking turned up the below.

If this approach is good, it may be worth including in examples. If not, what is the recommended approach, and is a ternary operator a reasonable feature request?

Thanks!

Duncan

        context.RegisterLogical("<=", (a, b) => a <= b, Precedence.Addition);
        context.RegisterLogical(">", (a, b) => a > b, Precedence.Addition);

        context.RegisterBinary("if",(a,b) => (b != 0) ? a : 0, Precedence.Addition);

        MathExpr expr = new MathExpr("({x} if {x} <= 0.5) + (({x} - 0.5) if ({x} > 0.5))", context);

        var fn = expr.Compile("x");

        Debug.Assert(IsNear(fn(0.0), 0));
        Debug.Assert(IsNear(fn(0.75), 0.25));

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.