matheval / expression-evaluator-c-sharp

Matheval is a mathematical expressions evaluator library written in C#. Allows to evaluate mathematical, boolean, string and datetime expressions
https://matheval.org/
MIT License
110 stars 30 forks source link

Improving calculation precision #5

Open astroman133 opened 2 years ago

astroman133 commented 2 years ago

Your package is very full featured, but the accuracy is often limited because the .NET System.Math class does not support the decimal data type for many of the functions that it provides. This includes Exp, Log, Log10, Pow, and all of the trig functions. The Pi and E constants are also only accessible as doubles. It is really unfortunate that Microsoft did not, and does not, provide the ability to perform all of these functions at the full resolution of the Decimal data type.

I created a simple program that uses your expression evaluator to take the square root of 2 and then multiply the result by itself. Here is the output from this program:

The original value is 2 The square root value is 1.414214 The root value squared is 2.000001237796

It is OK out to 5 decimal places and if Double precision is adequate for a user's needs, then what you have is perfectly fine, but you should not say that your library "Uses Decimal for calculation and result" without a warning about the many functions that only use Double resolution.

What is needed for those users with requirements for full Decimal precision is to supplement the System.Math class with a class that provides the ability to do all the supported calculations at full Decimal resolution. The DecimalMath library from Nathan P. Jones seems to fill that need nicely. For full disclosure, I have no interest in the DecimalMath package, and while I am using it, I cannot vouch for its accuracy or suitability for your needs.

Here is the output of the same calculation using the DecimalMath.DecimalEx.Sqrt function.

The original value is 2 The square root value using DecimalMath is 1.414213562373095048801688724 The root value squared is 2

You can find out more info about DecimalMath here: https://nathanpjones.com/2015/05/introducing-decimalmath/

It would be very useful if your expression evaluator could incorporate full Decimal precision throughout. It should not be too difficult to incorporate the DecimalMath package into your code, or even just use the parts that you need directly. It is definitely worth investigating.

I attached my test program source code for your convenience.

Thanks!

Rick Burke astroman133@gmail.com

Program.txt