0

in trying to find the absolute distances (of a vector of values) from a number, and then converting these values into character, a value changed. I tried a naive search, unsuccessfully, but I'm not sure I know how to search on this subject.

An example:

abs(1.7 - seq(1, 2, 0.2))
#[1] 0.7 0.5 0.3 0.1 0.1 0.3
as.character(abs(1.7 - seq(1, 2, 0.2)))
#[1] "0.7"     "0.5"      "0.3"    "0.0999999999999999"     "0.1"    "0.3"
as.character(1.7 - seq(1, 2, 0.2)) # same happens without abs() function
#[1] "0.7"    "0.5"    "0.3"    "0.0999999999999999"    "-0.1"     "-0.3"

I tried on more examples but the as.character() values are not always changed. Can someone explain what is happening?

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
alexis_laz
  • 12,884
  • 4
  • 27
  • 37
  • It remains unclear what your issues are. Are you being surprised that 1.7 minus 1.6 is not what you expected? In which case read the R-FAQ. – IRTFM Oct 05 '13 at 18:26
  • My question is why an -apparently- correct subtraction is changed when is converted to character. I've tried R-FAQ, and tried it again now, but I can't figure out what to look for. – alexis_laz Oct 05 '13 at 19:10
  • Try this: `abs(1.7 - seq(1, 2, 0.2))[4]==.1` then look at [this](http://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal). – Thomas Oct 05 '13 at 19:18
  • You may want the `round` function. – IRTFM Oct 05 '13 at 19:25
  • @Thomas: The truth is I was aware of those "test-equality issues" but your comment pushed me to dig it even more and I found that I should have gone with `format()` instead of `as.character()`. I guess I should thank you, then. :) – alexis_laz Oct 05 '13 at 19:43
  • @DWin: `round` was my first attempt to solve this, but I needed those computations in an another function, where I would not always know the number of decimal digits. Thank you, though. – alexis_laz Oct 05 '13 at 19:46
  • Why are you converting to `character` in the first place? If you want to format your results, use `print` or `sprintf` or equivalent. – Carl Witthoft Oct 05 '13 at 20:23
  • @CarlWitthoft: I needed to `strsplit` my results. I could have used `sprintf`, though, to begin with. – alexis_laz Oct 05 '13 at 20:38

0 Answers0