-3

If I have something like this:

double a = 1.0f;
double b = 1.0f;
double c = 1.0f;
double d = 1.0f;

a /= 3.0f;    // 0.3333...
b /= 3.0f;
c /= 3.0f;

if ((a+b+c) == 1)
    puts("sum equals 1");
if (3*a == 1)
    puts("product equals 1");
if (d == 1)
    puts("d equals 1");

Unsurprisingly, only the 3rd one executes. Is there a simple way to execute a code if a sum of some independent variables equals exactly 1?

Edit: I really know why (1/3.0) + (1/3.0) + (1/3.0) is not 1. But I didn't know another way to ask it.

Cn00b
  • 3
  • 2
  • See http://stackoverflow.com/questions/4858531/double-equals-0-problem-in-c – zr. Feb 16 '13 at 07:41
  • [What Every Programmer Needs to Know About Floating Point](http://floating-point-gui.de/). (1/3.0) + (1/3.0) + (1/3.0) will **never** equal 1.0 in any finite-representation binary floating point system. Best you can do is ask if they approximately equal 1 within a tiny threshold. – nneonneo Feb 16 '13 at 07:41
  • I know why it doesn't work. The question is how could I do it so the sum does works – Cn00b Feb 16 '13 at 07:44
  • 1
    You can't. That's the simple truth. – nneonneo Feb 16 '13 at 07:44
  • Why are you using `float` literals (like `1.0f` instead of `1.0`) while your variables are actually `double`? – Nikos C. Feb 16 '13 at 07:44
  • dunno. I think they where initialy float and I didn't think they could hurt – Cn00b Feb 16 '13 at 07:49

1 Answers1

0

Try to print a+b+c as well as a+b+c-1 and compare the results. You will notice that the result of a+b+c-1 is not exactly 0. This is always an issue as floating point arithmetic does not offer infinite precision.

One possible solution is to test for abs(a+b+c-1) smaller some threshold. Another solution is to switch to an implementation without floating point, e.g. representations with numerator, denumerator. Another solution would be to implement intervall arithmetic and to check if zero is contained in the result.

The best solution in your case depends on what you are actually trying to achieve.

Udo Klein
  • 6,784
  • 1
  • 36
  • 61