0

Somewhere I found this code

signdig = function(x)
{
  length(gregexpr("[[:digit:]]", as.character(x))[[1]])
}

But this returns strange numbers, like

> L=matrix(c(15,5,9,3.111),nrow=2)
> kappa(L)
[1] 239.5819 
> signdig(kappa(L))
[1] 15

Can somebody suggest an algorithm or code to solve it?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Harshvardhan
  • 479
  • 1
  • 3
  • 12
  • 1
    `round(kappa(L))` – Adam Quek Jun 05 '17 at 08:53
  • We can use `signif(kappa(L))` – akrun Jun 05 '17 at 08:54
  • 1
    I think the question is about finding the number of significant digits a number currently has, not formatting it to a certain number of digits? – Marius Jun 05 '17 at 08:58
  • @Marius is right. `round(kappa(L))` rounds it. `signif(kappa(L))` rounds it to six digits. – Harshvardhan Jun 05 '17 at 09:08
  • 1
    I am able to solve it to a limited extent (i.e. for decimals) using this: ` s = function(n) { i=0 while(n%%10!=0) { i=i+1 n=n*10 } return(i) }` – Harshvardhan Jun 05 '17 at 09:44
  • @Harshvardhan you say that the answer for `signdig(kappa(L))` (15) is strange, but no, that is correct. I suspect that you think it is strange because `kappa(L)` showed 239.5819 as the result - 7 digits, right? No. R just displays 7 digits by default. Try `options(digits=15)` THEN try `kappa(L)`. – G5W Jun 05 '17 at 14:39

1 Answers1

2

In the interest of simplicity, let's assume that all of the values in L are precise to the third decimal place and that kappa(L) is also precise to the third decimal place. Let's also assume a convention such that a value has a precision attribute (denoted pa) equal to its order of magnitude. Thus, all of the values in L have a precision attribute of -3.

Then the count of significant figures in kappa(L) is

sigfig = ceiling(log10(abs(x))) - precision + (log10(abs(x)) %% 1 == 0)

as a general function

count_sigfig <- function(x, precision){
  ceiling(log10(abs(x))) - precision + log10(abs(x)) %% 1 == 0)
}
Benjamin
  • 16,897
  • 6
  • 45
  • 65