Harshvardhan
Harshvardhan

Reputation: 559

Is there a function in R, which returns number of significant digits?

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?

Upvotes: 0

Views: 394

Answers (1)

Benjamin
Benjamin

Reputation: 17369

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)
}

Upvotes: 2

Related Questions