[Rd] compairing doubles
Felix Ernst
felix@gm@ern@t @ending from outlook@com
Thu Aug 30 11:27:38 CEST 2018
Dear all,
I a bit unsure, whether this qualifies as a bug, but it is definitly a strange behaviour. That why I wanted to discuss it.
With the following function, I want to test for evenly space numbers, starting from anywhere.
.is_continous_evenly_spaced <- function(n){
if(length(n) < 2) return(FALSE)
n <- n[order(n)]
n <- n - min(n)
step <- n[2] - n[1]
test <- seq(from = min(n), to = max(n), by = step)
if(length(n) == length(test) &&
all(n == test)){
return(TRUE)
}
return(FALSE)
}
> .is_continous_evenly_spaced(c(1,2,3,4))
[1] TRUE
> .is_continous_evenly_spaced(c(1,3,4,5))
[1] FALSE
> .is_continous_evenly_spaced(c(1,1.1,1.2,1.3))
[1] FALSE
I expect the result for 1 and 2, but not for 3. Upon Investigation it turns out, that n == test is TRUE for every pair, but not for the pair of 0.2.
The types reported are always double, however n[2] == 0.1 reports FALSE as well.
The whole problem is solved by switching from all(n == test) to all(as.character(n) == as.character(test)). However that is weird, isn�t it?
Does this work as intended? Thanks for any help, advise and suggestions in advance.
Best regards,
Felix
[[alternative HTML version deleted]]
More information about the R-devel
mailing list