Mathematical Expression using NCalc - c#

I am trying understand the expression library NCalc.
http://ncalc.codeplex.com
If I have a script as below,
SET A = CLOSE - OPEN;
SET B = A>0.5 AND CLOSE > HIGH
If(HIGH > 5, ROC(CLOSE), B)
CLOSE is a List of double,
OPEN is a List of double,
HIGH is a List of double
AND ROC is a custom function which takes any List of double as input parameter and returns a list as output.
Can someone advice me if I can use NCalc library to parse this script? I couldn't find any documentation at Codeplex website.
Is there any where I could obtain the help file or documentation for NCalc?
Thanks a million.

yes you can. first two will be very straightforward for third you will just have to create your custom IF and ROC function

Related

Spliting a number into equal parts and Add it together to get the same number

I need to implement a logic in c# where as I need to split and Add it to together to get the same value.
For example:
1.0/6.0442137639369475 = 0.16544749061764519
and when I add
0.16544749061764519 + 0.16544749061764519
to make it 1.0 is not working at all it comes as
0.99268494370587
not 1.0 exactly.
I am not sure what I am missing...?
Try to use more precise dataformats. Try to use double. If this is not precise enough, what I doubt, you can still search for a more precise implementation.
if I guess your question correct, you want to do the following math:
c=a/b
d=c+c+c+... n-times until a==d.
this will only work if you use integer numbers for a and b, with your real number 6.0442137639369475 as b it cannot (math law afaik).
And by the way:
your division result 0.16544749061764519 is rounded! The correct result is 0.16544749061764518326.
So you maybe need another data type as already pointed out.

Find Critical Chi Square Value using MathNet.Numerics

So I want to get Critical Chi-Square Value using Significance level and Degrees of Freedom. I tried using MathNet.Numerics but couldn't find which method to use to get the Critical Chi-Square Value
This was the documentation I'm referring, any help on redirecting me to correct documentation would help.
How I calculate the value in Excel is by using the formula =CHISQ.INV.RT(A2,B2)
The function you require is InvCDF(), it is used as follows:
MathNet.Numerics.Distributions.ChiSquared.InvCDF(degreesOfFreedom, probability);
I could finally solve this problem, so I want to share how I solved it.
I used the MathNet library, and to use the same function of Excel you are providing you have to keep in mind a few things: in this library it does not exist =CHISQ.INV.RT itself, instead, in C#, you need to use InvCDF (the equivalent of =CHISQ.INV in Excel) but instead of using a probability parameter like 0.05, you have to use the opposite part of the interval (0, 1), so that parameter should be 0.95.
The logic of this is in the description of the functions in Excel.
"CHISQ.INV" description says "Returns the inverse of the left-tailed probability of the chi-squared distribution", this one is the equivalent of ChiSquared.InvCDF (C#).
"CHISQ.INV.RT" description says "Returns the inverse of the right-tailed probability of the chi-squared distribution", this one DOES NOT exist in the MathNet library.
Example:
In Excel you write
=CHISQ.INV.RT(0.05, 9)
In C# you write
ChiSquared.InvCDF(9, 0.95);
In both cases the answer will be 16.9189776
Note that the order of the parameters are switched.
I hope I could help with this.

User can write function in Windows Application

I need to develop C# application where a user can call some customized functions that have been developed by us, that have to be executed at run time.
For example, suppose I have developed a class which has the following methods:
Sum(params int[] values )
GreaterThan(int Value,int CompareValue).
Now I want to provide a User Interface to the user, where they can call these in nested manner. For example:
GreaterThan(Sum(1,5,6,8),15)
My application then will then parse this and execute the functions accordingly. How do I approach this?
Hope my requirement is clear and will get some solutions to this.
You can use NCalc mathematical expressions evaluator, it can evaluate expressions, for example
Expression e = new Expression("2 + 3 * 5");
Debug.Assert(17 == e.Evaluate());
for your requirements, you may need to write your own functions, check below answer :
How to add a new function to Ncalc

solving a math expression

I want to evaluate a math expression which the user enters in a textbox. I have done this so far
string equation, finalString;
equation = textBox1.Text;
StringBuilder stringEvaluate = new StringBuilder(equation);
stringEvaluate.Replace("sin", "math.sin");
stringEvaluate.Replace("cos", "math.cos");
stringEvaluate.Replace("tan", "math.tan");
stringEvaluate.Replace("log", "math.log10");
stringEvaluate.Replace("e^", "math.exp");
finalString = stringEvaluate.ToString();
StringBuilder replaceI = new StringBuilder(finalString);
replaceI.Replace("x", "i");
double a;
for (int i = 0; i<5 ; i++)
{
a = double.Parse(finalStringI);
if(a<0)
break;
}
when I run this program it gives an error "Input string was not in a correct format." and highlights a=double.Parse(finalStringI);
I used a pre defined expression a=i*math.log10(i)-1.2 and it works, but when I enter the same thing in the textbox it doesn't.
I did some search and it came up with something to do with compiling the code at runtime.
any ideas how to do this?
i'm an absolute beginner.
thanks :)
The issue is within your stringEvaluate StringBuilder. When you're replacing "sin" with "math.sin", the content within stringEvaluate is still a string. You've got the right idea, but the error you're getting is because of that fact.
Math.sin is a method inside the Math class, thus it cannot be operated on as you are in your a = double.Parse(finalStringI); call.
It would be a pretty big undertaking to accomplish your goal, but I would go about it this way:
Create a class (perhaps call it Expression).
Members of the Expression class could include Lists of operators and operands, and perhaps a double called solution.
Pass this class the string at instantiation, and tear it apart using the StringBuilder class. For example, if you encounter a "sin", add Math.sin to the operator collection (of which I'd use type object).
Each operator and operand within said string should be placed within the two collections.
Create a method that evaluates the elements within the operator and operand collection accordingly. This could get sticky for complex calculations with more than 2 operators, as you would have to implement a PEMDAS-esque algorithm to re-order the collections to obey the order of operations (and thus achieve correct solutions).
Hope this helps :)
The .Parse methods (Int.Parse, double.Parse, etc) will only take a string such as "25" or "3.141" and convert it to the matching value type (int 25, or double 3.141). They will not evaluate math expressions!
You'll pretty much have to write your own text-parser and parse-tree evaluator, or explore run-time code-generation, or MSIL code-emission.
Neither topic can really be covered in the Q&A format of StackOverflow answers.
Take a look at this blog post:
http://www.c-sharpcorner.com/UploadFile/mgold/CodeDomCalculator08082005003253AM/CodeDomCalculator.aspx
It sounds like it does pretty much what you're trying to do. Evaluating math expressions is not as simple as just parsing a double (which is really only going to work for strings like "1.234", not "1 + 2.34"), but apparently it is possible.
You can use the eval function that the framework includes for JScript.NET code.
More details: http://odetocode.com/code/80.aspx
Or, if you're not scared to use classes marked "deprecated", it's really easy:
static string EvalExpression(string s)
{
return Microsoft.JScript.Eval.JScriptEvaluate(s, null, Microsoft.JScript.Vsa.VsaEngine.CreateEngine()).ToString();
}
For example, input "Math.cos(Math.PI / 3)" and the result is "0.5" (which is the correct cosine of 60 degrees)

evaluate an arithmetic expression stored in a string (C#)

I'm working on a application in C# in which I want to calculate an arithmetic expression that is given as a string.
So like I got a string:
string myExpr="4*(80+(5/2))+2";
And I want to calculate the outcome of the arithmetic expression.
While in a language such as Javascript, PHP etc. you could just use Eval to do the trick this doesnt seem to be an option in C#.
I suppose it is possible to write a code to devide it into countless simple expressions, calculate them and add them together but this would take quite some time and I'm likely to have lots of troubles in my attempt to do so.
So... my question, Is there any 'simple' way to do this?
There's a javascript library you can reference, then just do something like:
var engine = VsaEngine.CreateEngine();
Eval.JScriptEvaluate(mySum, engine);
Edit;
Library is Microsoft.JScript
You could just call the JScript.NET eval function. Any .NET language can call into any other.
Have you seen http://ncalc.codeplex.com ?
It's extensible, fast (e.g. has its own cache) enables you to provide custom functions and varaibles at run time by handling EvaluateFunction/EvaluateParameter events. Example expressions it can parse:
Expression e = new Expression("Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)");
e.Parameters["Pi2"] = new Expression("Pi * Pi");
e.Parameters["X"] = 10;
e.EvaluateParameter += delegate(string name, ParameterArgs args)
{
if (name == "Pi")
args.Result = 3.14;
};
Debug.Assert(117.07 == e.Evaluate());
It also handles unicode & many data type natively. It comes with an antler file if you want to change the grammer. There is also a fork which supports MEF to load new functions.
It also supports logical operators, date/time's strings and if statements.
I've used NCalc with great success. It's extremely flexible and allows for variables in your formulas. The formula you listed in your question could be evaluated this easily:
string myExpr = "4*(80+(5/2))+2";
decimal result = Convert.ToDecimal(new Expression(myExpr).Evaluate());
You need to implement an expression evaluator. It's fairly straightforward if you have the background, but it's not "simple". Eval in interpreted environments actually re-runs the language parser over the string; you need to emulate that operation, for the bits you care about, in your C# code.
Search for "expression evaluators" and "recursive descent parser" to get started.
If you have Bjarne Stroustrup's The C++ Programming Language, in Chapter 6 he explains step by step (in C++) how to do exactly what Chris Tavares suggests.
It's straightforward but a little heady if you're not familiar with the procedure.
I needed to do something similar for an undergrad projectand I found this
Reverse Polish Notation In C#
Tutorial and code to be extremely valuable.
It's pretty much just an implementation of converting the string to Reverse Polish Notation then evaluating it. It's extremely easy to use, understand and add new functions.
Source code is included.
Try something like this:
int mySum = 4*(80+(5/2))+2;
var myStringSum = mySum.toString();

Categories