user6490531
user6490531

Reputation: 11

MathNet real double precision issue

I need to write a function to compare the string value "15.0000000000000001" to "15" and I am using MathNet. Using MathNet.Symbolics.Expression.Real only accepts double. When I do the following

Expression valOne = Expression.Real(Double.Parse("15.0000000000000001"));
Expression valTwo = Expression.Real(Double.Parse("15"));

valOne.Equals(valTwo);

The above evaluates to true.Double.Parse 15.0000000000000001 returns 15. I understand the 0's after the decimal is meaningless to double and it has storage limitations.

Could anybody please help?

Upvotes: 1

Views: 181

Answers (1)

simon at rcl
simon at rcl

Reputation: 7344

As a rule of thumb, a Float can hold up to 14 contiguous digits as well as a power of 10. So e.g. it will store 12.345678901234 as 1.2345678901234with the power being 1: multiple the two numbers together and you get the stored number.

In your example, you have a span of 18 digits from the first 1 to the last 1. Float can't store that in the available space so it drops the least significant bits - in this case the final 1. This the two numbers in your example should match.

However if you compared 12.345678901234 to 12.345678901235 then would not be equal.

Note that the 14 decimal digits I mention is a rule of thumb. Depending on the value of those digits it might be less.

And yes: this does mean that Floats are not exact, they are approximations.

Upvotes: 2

Related Questions