Skip to content
Prev 299473 / 398503 Next

number of decimal places in a number?

Hi Petr,

I think sprintf and formatC are identical as it can round >22 decimal places as opposed to print and signif
print(pi,digits=35)
Error in print.default(pi, digits = 35) : invalid 'digits' argument
?signif(pi,digits=22)
[1] 3.141593
a<-sprintf("%.35f",pi)
a
[1] "3.14159265358979311599796346854418516"
b<-formatC(pi,digits=36)
?b
[1] "3.14159265358979311599796346854418516"

?identical(a,b)
[1] TRUE


identical(a,signif(pi,digits=35))
[1] FALSE


A.K.



----- Original Message -----
From: Petr Savicky <savicky at cs.cas.cz>
To: r-help at r-project.org
Cc: 
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:
Hi.

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
using

?  sprintf("%20.17f", x)

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.

Petr Savicky.

______________________________________________
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.