Casting to double fails

Topics: Help
Mar 6, 2013 at 3:47 PM
Hi.

Just trying this lib out, but I ran into some problems when trying to "save" the Evaluation to a double variable. I get the error "Specified cast is not valid".

My code is something like this (a bit edited):
string formel = "x+2";
Expression e = new Expression(formel);
e.Parameters["x"] = 2.5;

double result = (double) e.Evaluate();  //gives error "Specified cast is not valid"
Any pointers on how to solve this?
Coordinator
Mar 6, 2013 at 7:19 PM
Try to cast it as a decimal.
Coordinator
Mar 6, 2013 at 7:19 PM
Or use Convert.ToDouble(...) if you really want a double.
Mar 7, 2013 at 8:47 AM
Hi.

Thx for quick response, I went with the decimal, and that worked.

How ever, I have some questions regarding performance of this library.
My code from the posting above has been used in a foreach-loop (testing with about 300000 items) evaluating formulas and x-values retrieved from linq to sql.

My first "problem" was that it was really slow when in debug-mode (VS 2010). The loop took over 3 minutes to complete, and took a lot of memory. If I run the same from a released .exe-file, it took 13 seconds to complete. That seems like a really big difference between debug and release? Any pointers to that?

My second issue is also regarding performance. I am also checking out the Dynamic Formula library (http://www.codeproject.com/Articles/25578/Dynamic-Formula-Processing-Library?msg=4509783#xx4509783xx) . Comparing these two solutions over the same data as above, NCalc takes 13 seconds and DynamicFormula takes only 7 seconds to complete.
Could it be that I use your solution in a less efficient way than I could have?
(I would like to use NCalc since it has more possibilities, but performance is very important for me).

Thanks for any insights you may have on these topics.
Mar 7, 2013 at 9:15 AM
Hi again.

I played around a little, checking first if the formula had changed and only used new Expression() if it had. Got it down to 1 second now.
Jan 20, 2016 at 12:30 PM
The code sample in the first post of this thread will also fail, even after your suggested 'fix', if instead of "2" you use "3.5" (for example).

i.e.
string formel = "x+3.5";
Expression e = new Expression(formel);
e.Parameters["x"] = 2.5;

var result = (decimal) e.Evaluate();

will fail with "Operator '+' can't be applied to operands of types 'decimal' and 'double'"

https://ncalc.codeplex.com/discussions/528933