0

I am stuck with this:

t1=1.698
t2=2.457
valuest=seq(t1, t2,by=10^(-3))

valuest[2] # I get 1.699

valuest[2]==1.699  # FALSE

Any help?

user12703198
  • 423
  • 3
  • 11
  • See: `sprintf("%.20f", valuest[2])` – GKi Jun 29 '20 at 17:24
  • and try `round(valuest[2], 3) == 1.699`, `round(valuest[2], 3) == valuest[2]` – GKi Jun 29 '20 at 17:26
  • Thank you! I try `round` and it now works! But I do not understand what `sprintf` would do and why I need to round a number which would not need rounding. – user12703198 Jun 29 '20 at 17:29
  • Comparing floating-point numbers for equality is almost always a bad idea. It is a fertile source of bugs. – John Coleman Jun 29 '20 at 17:31
  • Use `all.equal(valuest[2], 1.699)` – GKi Jun 29 '20 at 17:32
  • See what you get from `sprintf("%.20f", valuest[2])` and what you get from `sprintf("%.20f", 1.699)`. – GKi Jun 29 '20 at 17:34
  • A similar question with more detailed answer: https://stackoverflow.com/questions/6874867/floating-point-issue-in-r – monte Jun 29 '20 at 17:46
  • I can see with `sprintf` that a different approximation is used. I guess it's never too late to learn some basics about coding. As far as I understand, equality should not be tested with `==` when dealing with not integer numbers. Is that correct? Thanks a lot to everybody! – user12703198 Jul 01 '20 at 07:01

0 Answers0