[R] number of decimal places in a number?
smartpink111 at yahoo.com
Sun Jul 8 20:39:22 CEST 2012
I think sprintf and formatC are identical as it can round >22 decimal places as opposed to print and signif
Error in print.default(pi, digits = 35) : invalid 'digits' argument
----- Original Message -----
From: Petr Savicky <savicky at cs.cas.cz>
To: r-help at r-project.org
Sent: Sunday, July 8, 2012 2:21 PM
Subject: Re: [R] number of decimal places in a number?
On Sat, Jul 07, 2012 at 01:12:34PM +0100, Ted Harding wrote:
> I had thought of also (as well as my numerical routing) suggesting
> a "gsub()" type solution like Joshua's below, but held back because
> the result could depend on how the number arose (keyboard input,
> file input, or from computation within R).
> However, I now also realise that (again because of binary rounding
> errors), the "gsub()" method has interesting differences from my
> numerical method. Example:
> [A] (as from my original method):
> #  7
> [B] (the "gsub()" method)
> nchar(gsub("(.*\\.)|(*$)", "", as.character(123456789.123456789)))
> #  6
> Now look at:
> [C] (what as.character() does to 123456789.123456789)
> #  "123456789.123457"
> [D] ("22" is the maximum number of decimal digits for print())
> #  123456789.1234568
> So as.character() has rounded it to 6 decimal places (agreeing
> with [B]), while using print() with the maximum of 22 digits
> (more than enough for the 18 digits in 123456789.123456789)
> rounds it to 7 decimal places (i.e. 16 digits in all), which
This difference is due to rounding to 15 digits in as.character().
This function rounds to 15 decimal digits, which is the maximum
number of digits, which can always be converted to binary
and back. Function print(, digits=22) prints the decimal
equivalent of the represented number. So, it is more accurate, but
its output may contain digits, which are purely the consequence
of inaccuracy of the representation.
The same output as from print(, digits=17) may be obtained
Of course, if the required number of digits is close to 17 or
even more, the last digits are the last digits of the represented
number, not of the intended result of the computation.
Hope this helps.
R-help at r-project.org mailing list
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help