1

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?

  • What kind of calculations or comparisons are you doing where you need 18 digits of absolute precision? – D Stanley Jun 21 '16 at 17:56
  • To put that in perspective - there are [approximately 7.5e18 grains of sand on earth](http://www.npr.org/sections/krulwich/2012/09/17/161096233). Does it really matter if you miscount by ten grains? – D Stanley Jun 21 '16 at 17:58

1 Answers1

2

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.

simon at rcl
  • 7,326
  • 1
  • 17
  • 24