Thursday 15 April 2010

.net - Does Math.Round(double, decimal) always return consistent results -


Of course, floating point value should never be understood, which results from calculation for equality, but always a Use small tolerance, like:

  double value1 = ... double value2 = ... if (Math.Abs ​​(value1 - value2) & tolerance * Math.Abs (Value1)} {... values ​​close enough}  

But if I use the monastery. Round can always be sure that the resulting value will be consistent, i.e. will always be successful on the following targets, even if the spherical value is a value? A double

  public static void TestRound (double value 1, double value 2, decimal int) {double roundedValue1 = math.Google (value 1, decimal) can not be displayed exactly ; Double round value 2 = Math. Round (value 2, decimal); String format = "n" + decimal. Toasting (); If (round value 1.ToString (format) == was rounded 2. 2. toaster (format) {// They had round, roundness accurate for the same value? Debug Asset (rounded velay = 1 == round value 2); }}  

If not, please provide a counterexpression.

Edit

Thank you for a counter code created by anger, the force which proves the results is not "consistent" in the normal case. In this counting example, there are 16 important digits in the result of the goal - it also fails in the same way when it is scaled:

  double value1 = 10546080000034341D; Double Value 2 = 10546080000034257D; Int decimal = 0; Test-round (value1, value2, decimal);  

Although I would also be interested in more mathematical details. More mathematical Stackoverflowers upvotes bonuses for anyone who can do any of the following tasks.

  • A counterexample where find 16 significant digits compared to the round result

  • Identify the range of values ​​for which

  • Give an algorithm method to generate the answer

I placed a breakpoint at">

and it entered with the following value

  value1 = 1.0546080000034341 value2 = 1.0546080000034257 decimal = 15 roundedValue1 = 1.0546080000034339 roundedValue2 = 1.0546080000034259 roundedValue1.ToString (format) = 1.054608000003430 roundedValue2.ToString (format) = 1.054608000003430  

I think the answer to this question was looking for you?

If not, please let me know, so I can do more tests.


No comments:

Post a Comment