[R] precision in seq

jim holtman jholtman at gmail.com
Tue Feb 5 21:38:37 CET 2008


If you want 0,0.05,0.1,...0.95,1.00  then think about encoding as characters:

> sprintf("%.2f", seq(0, 1, 0.05))
 [1] "0.00" "0.05" "0.10" "0.15" "0.20" "0.25" "0.30" "0.35" "0.40"
"0.45" "0.50" "0.55"
[13] "0.60" "0.65" "0.70" "0.75" "0.80" "0.85" "0.90" "0.95" "1.00"
>

then you won't have the problem of dealing with floating point
numbers, and still have the ability to later convert the character
strings back to numeric for processing.  Character strings will give
you the "exact" matches that you were expecting (but won't get) with
floating point.

On 2/5/08, Eric Elguero <Eric.Elguero at mpl.ird.fr> wrote:
> thank you to all who answered.
>
>
> > 0+0.05+
> + 0.05+0.05+0.05+0.05+0.05+0.05+
> + 0.05+0.05+0.05+0.05+0.05+0.05+
> + 0.05+0.05+0.05+0.05+0.05+0.05 - 0.95
> [1] 3.330669e-16
>
> > seq(0,1,0.05)[20] - 0.95
> [1] 1.110223e-16
>
> > 0+19*0.05 - 0.95
> [1] 1.110223e-16
>
> so this is the way seq calculates. I would have guessed
> that addition was more accurate than multiplication,
> but that is not the case.
>
> this one however bothers me:
> > 19/20-0.95
> [1] 0
>
>
> I noticed this problem when I tried to extract rows of a matrix
> according to whether values of some vector where in the set
> (0,0.05,...,0.95,1), with something like x%in%seq(0,1,0.05)
> Now I understand that I should not use this construction
> unless x is of type integer. Would you agree?
>
> Eric Elguero
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>


-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?



More information about the R-help mailing list