0

So the issue is .1 + .2 =/= .3

The language is R.

I have a bunch of fractions that in the end should sum to 1. And I have an assert statement that fails because this invariant does not always hold true due to this issue.

What is the best solution?

  • 1
    What does "best" mean exactly? There seem to be plenty of discussion at the existing question: https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal. The "best" solution is to change your code so it doesn't rely on floating point numbers to exactly equal some floating point value. – MrFlick Jun 17 '19 at 15:30
  • This may be a bit hacky, but in cases such as these I usually simply resort to asserting that `abs(1-val) < .000000000000001` – abcalphabet Jun 17 '19 at 15:31
  • Well, as pointed out in the other question `all.equal()` is probably a better choice in general. – MrFlick Jun 17 '19 at 15:32
  • Do you want to change the numbers so the assert holds, or do you want to change the assert so it accepts the numbers? Is the purpose of the assert to detect a bug in the code or to protect some following computation that needs a sum of exactly one or something else? – Eric Postpischil Jun 17 '19 at 19:53
  • If you are just testing for a bug in the code, change the assert to accept values near one. It will still detect most bugs. If a following computation relies on the sum being exactly one, change it to be more tolerant. If you cannot change it, there are other Stack Overflow questions about fudging a sequence of numbers to make sum exactly one. – Eric Postpischil Jun 17 '19 at 19:56

0 Answers0