# Re: [R] Number of digits of a value for problem 7.31 RFAQ SOLVED not really

From: Matthieu Stigler <stigler3_at_etu.unige.ch>
Date: Mon, 18 Feb 2008 16:16:51 +0100

Matthieu Stigler a e'crit :

```> Richard.Cotton_at_hsl.gov.uk a e'crit :
```

>>>> What I mean is if R shows 2.3456 I want to obtain the info that
>> digits=4
>>>> even if in facts the value has more (internal) digits.
>>> Try:
>>> x = 1.23456789
>>> format(x, nsmall=20)
>>> # [1] "1.23456788999999989009"
>>
>> I've just re-read the question. I suspect what you really wanted was
>> something like:
>>
>> getndp <- function(x, tol=2*.Machine\$double.eps)
>> {
>> ndp <- 0
>> while(!isTRUE(all.equal(x, round(x, ndp), tol=tol))) ndp <- ndp+1
>> if(ndp > -log10(tol)) warning("Tolerance reached, ndp possibly
>> underestimated.")
>> ndp }
>>
>> x = 0.123456
>> getndp(x)
>> # [1] 6
>>
>> x2 <- 3
>> getndp(x2)
>> # [1] 0
>> x3 <- 0.1234567890123456789
>> getndp(x3)
>> # [1] 16
>> # Warning message:
>> # In getndp(x3) : Tolerance reached, ndp possibly underestimated.
>>
>> Regards,
>> Richie.
>>
>> Mathematical Sciences Unit
>> HSL
>>
```>
> Nice! Thanks a lot!!
> Now I can solve my problem that:
>
> target<-0.223423874568437
> target<=target+0.1-0.1 #TRUE
> target>=target+0.1-0.1 #FALSE!!
> target==target+0.1-0.1 #FALSE!!
>
> by:
> target<=round(target+0.1-0.1, getndp(target)) #TRUE
> target>=round(target+0.1-0.1, getndp(target)) #TRUE!!
> target==round(target+0.1-0.1, getndp(target)) #TRUE!!
>
>
```

Actually (after some trials) there is a little problem when faced with zeros...

>getndp(1.0)
[1] 0

Note that it is only a partial problem because this happens only when the value is taken with other and so
max(apply(matrix(allvalues,1,getndp))) will give the expected answer.

But when faced with only one value...

a<-as.character(1.23134)
b<-strsplit(a,"\\.")

nchar(b)
But I don't see how to do so that I can extract only the second element (maybe otherwise with sub or grep?)... But the method you gave is really more reliable than my "makeshift repair"

Thanks again!

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. Received on Mon 18 Feb 2008 - 15:23:04 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 18 Feb 2008 - 16:30:15 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.