-1

I am facing a floating-point problem related to the sum of probabilities. It is really difficult to prove that sum of probabilities is 1 because of some minor differences. The MWE is as follows.

p1=0.99999999

p2=0.00000000003

p1+p2==1

[1] FALSE

The sum of probabilities is approximately 1. The difference from 1 is 1-p1-p2 = 9.97e-09, that is very small. I need to apply the sum of probabilities conditions in my many functions. But the execution is halted because of floating-point.

Could anyone please guide me about that?

Thank you

Regards

Shaami
  • 11
  • 2
  • 1
    Read : https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal – Ronak Shah Aug 20 '20 at 08:03
  • We have seen this or similar questions before, like [this one](https://stackoverflow.com/questions/17641300/rounding-floats-so-that-they-sum-to-precisely-1). I think there was something tied to R, but I do not have time to search at the moment. One thing you should add to the question is specific information about why “execution is halted.” Is R enforcing some constraint that the probabilities must be one, and you need a way to work around this? Or is your software choosing to halt? Why, what are the specific steps leading to that? – Eric Postpischil Aug 20 '20 at 09:21
  • Hi, Eric Thank you. I got it. Execution is halted because I have put a stop function when the sum of probabilities id not equal to one that is because of floating-point problems. I need to set some tolerance comparison to compare the sum of probabilities. Many many thanks. – Shaami Aug 20 '20 at 10:08

1 Answers1

0

The general principle when comparing floating point numbers is not to test for equality, but to test whether the difference is less than some epsilon, i.e. the maximum difference you'll accept as "being equal". In your case, you'd test for abs(p1+p2-1) < epsilon. Search for floating point comparisons, there's lots of documentation and discussion all over the web, e.g. How should I do floating point comparison?

Pablo Pretzel
  • 148
  • 13