-2

I'm using NCalc to evaluate complex expressions. But I've found a major problem.

A simple formula like new Expression("Abs(-1) + Cos(2)").Evaluate() throws the exception

Operator '+' can't be applied to operands of types 'decimal' and 'double

In C# code Math.Abs(-1) + Math.Cos(2) works, so either I'm doing something wrong or there is a bug in NCalc.

Does anyone have the same problem?

Does anyone have a solution?

The only thread i found on the project's website related to this error is quite old and talks about editing the source code. https://ncalc.codeplex.com/discussions/346702

I also posted a question on their forum but StackOverflow is usualy more dynamic. https://ncalc.codeplex.com/discussions/613634

pitermarx
  • 908
  • 1
  • 9
  • 22

2 Answers2

2

Ok. I looked at the source code. And here is what I found.

The Abs(-1) part of the expression is always evaluated as a decimal

Result = Math.Abs(Convert.ToDecimal(
                        Evaluate(function.Expressions[0]))
                        );

Cos(2) is evaluated as double

Result = Math.Cos(Convert.ToDouble(Evaluate(function.Expressions[0])));

And C# does not allow you to add these two types together.

The reason that Math.Abs(-1) + Math.Cos(2) works is that Math.Abs(-1) actually evaluates as int. And you can perfectly add an int to double.

You can not compile this piece for example (note m for decimal). Math.Abs(-1m) + Math.Cos(2); which is actually what NCalc is trying to do when you type out

new Expression("Abs(-1) + Cos(2)").Evaluate()

I would call this a bug. You can try to edit the source and try to fix this problem or find some other option.

btevfik
  • 3,391
  • 3
  • 27
  • 39
  • Thanks. The project although stable and usable, seems a bit abandoned. I guess the only option is to try to fix this – pitermarx Mar 25 '15 at 16:06
  • It appears the issue has been solved already. its just not deployed as a version https://ncalc.codeplex.com/SourceControl/changeset/5a719518101d – pitermarx Mar 25 '15 at 16:28
  • 1
    I saw that the issue was solved in the latest source but not deployed anywhere, so i created a clone in [github](https://github.com/pitermarx/ncalc-edge), linked to [AppVeyor](https://ci.appveyor.com/project/pitermarx/ncalc-edge) and published to [Nuget](https://www.nuget.org/packages/NCalc-Edge/) I also [started](https://github.com/pitermarx/ncalc2) a new [project](https://ci.appveyor.com/project/pitermarx/ncalc2) that intends to [upgrade](https://www.nuget.org/packages/NCalc2) antlr to version 4 – pitermarx Mar 26 '15 at 14:27
0

After a brief chat with btevfik (helpfull fella) we have come to the conclusion that this is a bug in NCalc. I guess I'll have to analyse the source and fix it.

I still accept answers though...

Community
  • 1
  • 1
pitermarx
  • 908
  • 1
  • 9
  • 22