[R] Rounding
Tony Plate
tplate at blackmesacapital.com
Thu Sep 19 16:59:59 CEST 2002
At 09:22 PM 9/19/2002 +1200, you wrote:
>Now my questions is: how do I work out the number of digits x has?
If you're working with decimal digits (as most people do) that would be
ceiling(log10(abs(x)))
for most cases. The problem cases are round powers of 10, such as 1000,
for which the above expression returns 3. You'll have to work out whether
or not that is appropriate for your task.
Another more indirect method is:
nchar(formatC(floor(abs(x)), format="f", digits=0))
which will tell you number of digits before the decimal point in an
infinite precision decimal rendition of x. E.g., it will return 4 for
1000, and 3 for 999.999999. The latter may or may not be what you want,
since 999.999999 usually prints as 1000 (because of rounding implicit in
printing).
-- Tony Plate
PS. If you do need to treat round powers of 10 as special cases, be sure
to test on many examples to make sure your arithmetic behaves correctly
when implemented with binary floating point arithmetic; here's a table
illustrating the challenges:
> cbind(i=i,"=="=log10(10**i)==i,"<"=log10(10**i)<i,">"=log10(10**i)>i)
i == < >
[1,] -6 0 0 1
[2,] -5 1 0 0
[3,] -4 0 0 1
[4,] -3 0 0 1
[5,] -2 0 0 1
[6,] -1 0 0 1
[7,] 0 1 0 0
[8,] 1 1 0 0
[9,] 2 1 0 0
[10,] 3 0 1 0
[11,] 4 1 0 0
[12,] 5 1 0 0
[13,] 6 0 1 0
[14,] 7 1 0 0
[15,] 8 1 0 0
[16,] 9 0 1 0
[17,] 10 1 0 0
[18,] 11 1 0 0
[19,] 12 0 1 0
[20,] 13 0 1 0
[21,] 14 1 0 0
[22,] 15 0 1 0
[23,] 16 1 0 0
[24,] 17 1 0 0
[25,] 18 0 1 0
[26,] 19 1 0 0
[27,] 20 1 0 0
[28,] 21 0 1 0
[29,] 22 1 0 0
[30,] 23 0 1 0
[31,] 24 0 1 0
>
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list