• 0

[C#] 0.125 * 8 = 1.0000000000000002


Question

Hey all,

I'm developing an application at the moment, which uses some stochastic matrices. And I've hit something of a problem. The rows of the matrix must all add up to one, and they do, however when I sum the values in the row together I get 1.0000000000000002 as the result! How has this happened?

I'm fairly sure it has something to do with the way double floating point numbers are stored, but I'm not sure quite what, and I don't know how to get around it!

Help!

-- Majesticmerc

Link to comment
Share on other sites

9 answers to this question

Recommended Posts

  • 0

Maybe just add a round() function in there. Like, if x > .999999998 && x < 1.00000000002, x = 1. It doesn't really fix the problem, but it'll help you get around it if it's nothing that important.

Link to comment
Share on other sites

  • 0

doubles should be ok in terms of accuracy, i assume you're using doubles throughout and not mixing doubles/floats?

if you're just using doubles, i guess you could do something like:

if (a &gt; 0.9999995 &amp;&amp; a &lt; 1.0000005) { // a == 1 }

Link to comment
Share on other sites

  • 0

I've considered it, and I might have to go for that, although it's not ideal. Are there any disadvantages (aside from memory use) to using decimals over doubles?

Link to comment
Share on other sites

  • 0

Guidelines from Code Complete 2nd edition for floating-point numbers :

Avoid additions and substractions on numbers that have greatly different magnitudes

Avoid equality comparison (like in your case, comparing if the sum of a row equals 0.0)

Anticipate rounding errors

Check language and library support for specific data types (such as Decimal in C#)

You could code a small static "Equals" routine along the lines of :

readonly double ACCEPTABLE_DELTA = 0.0000001;
bool Equals(double num1, double num2) {
	return (Math.abs(num1 - num2) &lt; ACCEPTABLE_DELTA);
}

Link to comment
Share on other sites

  • 0

Thanks for the information guys, you've helped me out so much here! I don't quite know how I'm going to solve this issue, but you've definitely helped me towards the solution!

:D

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.