Re: [R] number of decimal places in a number?

2012-07-10 Thread Martin Ivanov
 
Dear R users,

Thank You very much for Your responsiveness. I think the suggestion of arun's 
modification of Josh's code works best and it is what I am going to implement.

Cite Ellison:
Surely the issue is not the particular numeric resolution of the numbers but 
the idea that the bounding box limits should be integer multiples of the 
resolution?
Is that not accomplished more straightforwardly by things like
min <- resol * floor( min(lat)/resol )
max <- resol * ceil( max(lat)/resol )
?
Dear Ellison,
not the bounding box limits, but the bounding box RANGE needs to be an integer 
multiple of the resolution, that is max-min=ineger*resolution. The bbox limits 
must just be rounded to the same number of digits as the resolution and include 
all available values, of course.

Best regards.



 > Оригинално писмо 
 >От:  arun 
 >Относно: Re: [R] number of decimal places in a number?
 >До:  ted.hard...@wlandres.net  
 >Изпратено на: Събота, 2012, Юли 7 22:50:03 EEST
 >
 >
 >Hi, 
 >
 >
 >I checked the count for the cases (A) and (F) with a variant of Josh's 
 >function:
 >
 >decimalnumcount<-function(x){stopifnot(class(x)=="character")
 > x<-gsub("(.*)(\\.)|([0]*$)","",x)
 > nchar(x)
 > }
 > A) 
 >x<-"123456789.123456789"
 > decimalnumcount(x)
 >#[1] 9
 >
 >x<-"923456789.123456789"
 >decimalnumcount(x)
 >#[1] 9
 >
 >B)
 > x<-"0.012345"
 > decimalnumcount(x)
 >#[1] 10
 >
 >
 >c)
 >x <- c("3.14", "3.142", "3.1400", 
 >"123456.123456789", "123456789.123456789",pi,sqrt(2))
 >  decimalnumcount(x)
 >#[1]  2  3  2  9  9 14 13
 >x
 >[1] "3.14"    "3.142"   
 >"3.1400" 
 >[4] "123456.123456789"    "123456789.123456789" 
 >"3.14159265358979"   
 >[7] "1.4142135623731"    
 >
 >
 >
 >D)
 > x <- c(3.14, 3.142, 3.1400, 123456.123456789, 123456789.123456789,pi,sqrt(2))
 >decimalnumcount(as.character(x) )
 >[1]  2  3  2  9  6 14 13
 >#as.character(x)
 >#[1] "3.14" "3.142"    
 >"3.14" "123456.123456789"
 >#[5] "123456789.123457" "3.14159265358979" 
 >"1.4142135623731" 
 >
 >E)
 >print(pi,22)
 >#[1] 3.141592653589793115998
 >print(sqrt(2),22)
 >#[1] 1.414213562373095145475
 >    x <- c("3.14", "3.142", "3.1400", 
 >"123456.123456789", 
 >"123456789.123456789","3.141592653589793115998","1.414213562373095145475")
 > decimalnumcount(x)
 >#[1]  2  3  2  9  9 21 21
 >
 >F) 
 >formatC(pi,format="f",digits=22)
 >#[1] "3.1415926535897931159980"
 > formatC(sqrt(2),format="f",digits=22)
 >#[1] "1.4142135623730951454746"
 >
 > x <- c("3.14", "3.142", "3.1400", 
 >"123456.123456789", 
 >"123456789.123456789",formatC(pi,format="f",digits=22),formatC(sqrt(2),format="f",digits=22))
 > decimalnumcount(x)
 >#[1]  2  3  2  9  9 21 22
 >
 >
 >G)
 >#  formatC() didn't show the limitations of print() 
 > print(sqrt(2),22)
 >#[1] 1.414213562373095145475
 >
 >print(sqrt(2),35)
 >#Error in print.default(sqrt(2), 35) : invalid 'digits' argument
 >
 >formatC(sqrt(2),35)
 >#[1] "1.4142135623730951454746218587388285"
 >or,
 >formatC(sqrt(2),format="f",digits=35)
 >#[1] "1.41421356237309514547462185873882845"
 >
 >
 >#using >22
 >
 >x <- c("3.14", "3.142", "3.1400", 
 >"123456.123456789", 
 >"123456789.123456789",formatC(pi,format="f",digits=35),formatC(sqrt(2),format="f",digits=50))
 > decimalnumcount(x)
 >#[1]  2  3  2  9  9 35 50
 >
 >
 >
 >
 >So, I guess it will be better to deal with character strings rather than 
 >using as.character.
 >A.K.
 >
 >
 >
 >
 >- Original Message -
 >From: "ted.hard...@wlandres.net" 
 >To: r-help@r-project.org
 >Cc: Martin Ivanov 
 >Sent: Saturday, July 7, 2012 8:12 AM
 >Subject: Re: [R] number of decimal places in a number?
 >
 >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 r

Re: [R] number of decimal places in a number?

2012-07-09 Thread Petr Savicky
On Mon, Jul 09, 2012 at 07:52:18AM -0500, Jim Plante wrote:
> I don't know how significant this is, but WolframAlpha's value of pi 
> disagrees with R's at about the 16th decimal:
>  
> Wpi->3.141592653589793238462643383279502884197169399375105
> ..^
> Rpi->3.14159265358979311599796346854418516
> 
> Probably not of interest to anyone but astronomers, nanotechnologists, and us 
> anal lurkers though. We went to the moon and back on two decimal places.

Hi.

This does not belong to this thread.

The reason for the difference is explained in ?double

  Double-precision values:

 All R platforms are required to work with values conforming to the
 IEC 60559 (also known as IEEE 754) standard.  This basically works
 with a precision of 53 bits, and represents to that precision a
 range of absolute values from about 2e-308 to 2e+308.

Pi in binary is

  
(11.001001110110101010001000110110100011000)01000110100110001001100011001...

and the brackets separate the first 53 significant bits. So, the double
precision pi, which is represented by these bits, is slightly smaller than
the exact value. The difference is not specific to R, but to the standard
computer arithmetic implemented in the hardware, which uses 53 bits.

Hope this helps.

Petr Savicky.

P.S. If you want to make further comments, please, open a new thread.

__
R-help@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.


Re: [R] number of decimal places in a number?

2012-07-09 Thread Jim Plante
I don't know how significant this is, but WolframAlpha's value of pi disagrees 
with R's at about the 16th decimal:
 
Wpi->3.141592653589793238462643383279502884197169399375105
..^
Rpi->3.14159265358979311599796346854418516

Probably not of interest to anyone but astronomers, nanotechnologists, and us 
anal lurkers though. We went to the moon and back on two decimal places.

Jim Plante

On Jul 8, 2012, at 1:39 PM, arun wrote:

> 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 
> To: r-help@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:
>> 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):
>>f(123456789.123456789)
>># [1] 7
>> 
>> [B] (the "gsub()" method)
>>nchar(gsub("(.*\\.)|([0]*$)", "", as.character(123456789.123456789)))
>># [1] 6
>> 
>> Now look at:
>> 
>> [C] (what as.character() does to 123456789.123456789)
>>as.character(123456789.123456789)
>># [1] "123456789.123457"
>> 
>> [D] ("22" is the maximum number of decimal digits for print())
>>print(123456789.123456789,22)
>># [1] 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
> 
> 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@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.
> 
> 
> __
> R-help@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.

__
R-help@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.


Re: [R] number of decimal places in a number?

2012-07-09 Thread S Ellison
 

> -Original Message-
> From:  Martin Ivanov
> I have the longitudes (lon) and latitudes (lat), and I have a 
> resolution (r), for example r = 0.004. The bounding box must 
> have the same number of digits as resolution. 
Surely the issue is not the particular numeric resolution of the numbers but 
the idea that the bounding box limits should be integer multiples of the 
resolution?

Is that not accomplished more straightforwardly by things like
 min <- resol * floor( min(lat)/resol )
 max <- resol * ceil( max(lat)/resol )

?

S Ellison***
This email and any attachments are confidential. Any use...{{dropped:8}}

__
R-help@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.


Re: [R] number of decimal places in a number?

2012-07-08 Thread arun
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 
To: r-help@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:
> 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):
>   f(123456789.123456789)
>   # [1] 7
> 
> [B] (the "gsub()" method)
>   nchar(gsub("(.*\\.)|([0]*$)", "", as.character(123456789.123456789)))
>   # [1] 6
> 
> Now look at:
> 
> [C] (what as.character() does to 123456789.123456789)
>   as.character(123456789.123456789)
>   # [1] "123456789.123457"
> 
> [D] ("22" is the maximum number of decimal digits for print())
>   print(123456789.123456789,22)
>   # [1] 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

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


__
R-help@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.


Re: [R] number of decimal places in a number?

2012-07-08 Thread Petr Savicky
On Sat, Jul 07, 2012 at 11:52:35AM +0300, Martin Ivanov wrote:
>  Dear R users,
> 
> I need a function that gets a number and returns its number of actual decimal 
> places.
> For example f(3.14) should return 2, f(3.142) should return 3, f(3.1400) 
> should also return 2
> and so on. Is such function already available in R? If not, could you give me 
> a hint how to achieve that?

Hi.

Try the following.

  getDigits <- function(x)
  {
  out <- format.info(x, digits=10)
  stopifnot(out[3] == 0)
  out[2]
  }

The function format.info() rounds the input number
to "digits" significant digits and then outputs the
width of the field for printing, the number of digits
after the decimal dot and some information on the exponent 
(out[3] == 0, if exponent is not used). So, the required
number of digits in the fractional part is out[2].

  getDigits(3.123456)

  [1] 6

Hope this helps.

Petr Savicky.

__
R-help@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.


Re: [R] number of decimal places in a number?

2012-07-08 Thread Petr Savicky
On Sun, Jul 08, 2012 at 11:39:22AM -0700, arun wrote:
> 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)

Hi Arun:

Thank you for pointing this out. Funtion formatC()
is easier to use and uses the same C level function
as sprintf().

Petr.

__
R-help@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.


Re: [R] number of decimal places in a number?

2012-07-08 Thread Petr Savicky
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):
>   f(123456789.123456789)
>   # [1] 7
> 
> [B] (the "gsub()" method)
>   nchar(gsub("(.*\\.)|([0]*$)", "", as.character(123456789.123456789)))
>   # [1] 6
> 
> Now look at:
> 
> [C] (what as.character() does to 123456789.123456789)
>   as.character(123456789.123456789)
>   # [1] "123456789.123457"
> 
> [D] ("22" is the maximum number of decimal digits for print())
>   print(123456789.123456789,22)
>   # [1] 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

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


Re: [R] number of decimal places in a number?

2012-07-07 Thread Bert Gunter
mod Ted's comments, I believe that for your situation (not too many digits
to represent, decimal point always present)

countDecDigits <-
function(x)nchar(sapply(strsplit(as.character(x),"\\."),"[",2))

is simple and should work. No need for regular expressions here.

-- Bert



On Sat, Jul 7, 2012 at 6:52 AM, Martin Ivanov  wrote:

>  Dear Mr Harding,
>
> Thank You very much for Your responsiveness.
>
>  >There would seem to be no clean general solution to this
>  >question. An important issue would be: What use do you
>  >want to put the result to?
>
> I need this trick for the following task.
> I am writing a function which has to determine the bounding box for a
> spatial data set. The bounding box is a matrix(c(minLon minLat, maxLon,
> maxLat)).
> I have the longitudes (lon) and latitudes (lat), and I have a resolution
> (r), for example
> r = 0.004. The bounding box must have the same number of digits as
> resolution.
> So I first have to truncate min(lon) and min(lat) to 3 decimal places,
> then take the ceiling of max(lat)*10^3 and max(lon)*10^3 divided by 10^3.
> So I have the
> maximal interval with resolution r for each variable (lat or lon). Then I
> have to determine
> the number of cells in each direction, which I take as
> ceiling((maxLat-minLat)/r) and
> ceiling((maxLon-minLon)/r). Here is an example of my code:
>
>  # get the first n digits from a number
> truncf <- function(x, digits) {
>  # some control:
>  for(i in c("x", "digits")) if(!(is.numeric(get(i)) && length(get(i)) ==
> 1)) stop(i, " in truncatef must be a  numeric scalar!");
>  ## make sure that digits is an integer:
>  if(as.integer(digits) - digits) stop("Please provide an integer digits to
> truncf!");
>
>  x <- trunc(x*10^digits)/10^digits;
>  x;
> }
>  for(i in 0:5) if(!(resolution*10^i - as.integer(resolution*10^i))) break;
>  lonMin <- truncf(x=min(lon), digits=i); lonMax <-
> ceiling(x=max(lon)*10^i)/10^i;
>  latMin <- truncf(min(lat), digits=i); latMax <-
> ceiling(x=max(lat)*10^i)/10^i;
>  cells.dim <- ceiling(c(lonMax - lonMin, latMax - latMin)/resolution);
>
>
> I hope this sheds more light on my issue.
>
> Best regards,
> Martin
>
> -
> Ãðàæäàíñêà îòãîâîðíîñò – Öåíèòå íà êîìïàíèèòå
>
> http://www.sdi.bg/onlineInsurance/?utm_source=gbg&utm_medium=txtLink&utm_content=home
>
> __
> R-help@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.
>



-- 

Bert Gunter
Genentech Nonclinical Biostatistics

Internal Contact Info:
Phone: 467-7374
Website:
http://pharmadevelopment.roche.com/index/pdb/pdb-functional-groups/pdb-biostatistics/pdb-ncb-home.htm

[[alternative HTML version deleted]]

__
R-help@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.


Re: [R] number of decimal places in a number?

2012-07-07 Thread arun
Hi, 


I checked the count for the cases (A) and (F) with a variant of Josh's function:

decimalnumcount<-function(x){stopifnot(class(x)=="character")
 x<-gsub("(.*)(\\.)|([0]*$)","",x)
 nchar(x)
 }
 A) 
x<-"123456789.123456789"
 decimalnumcount(x)
#[1] 9

x<-"923456789.123456789"
decimalnumcount(x)
#[1] 9

B)
 x<-"0.012345"
 decimalnumcount(x)
#[1] 10


c)
x <- c("3.14", "3.142", "3.1400", "123456.123456789", 
"123456789.123456789",pi,sqrt(2))
  decimalnumcount(x)
#[1]  2  3  2  9  9 14 13
x
[1] "3.14"    "3.142"   "3.1400" 
[4] "123456.123456789"    "123456789.123456789" "3.14159265358979"   
[7] "1.4142135623731"    



D)
 x <- c(3.14, 3.142, 3.1400, 123456.123456789, 123456789.123456789,pi,sqrt(2))
decimalnumcount(as.character(x) )
[1]  2  3  2  9  6 14 13
#as.character(x)
#[1] "3.14" "3.142"    "3.14" "123456.123456789"
#[5] "123456789.123457" "3.14159265358979" "1.4142135623731" 

E)
print(pi,22)
#[1] 3.141592653589793115998
print(sqrt(2),22)
#[1] 1.414213562373095145475
    x <- c("3.14", "3.142", "3.1400", "123456.123456789", 
"123456789.123456789","3.141592653589793115998","1.414213562373095145475")
 decimalnumcount(x)
#[1]  2  3  2  9  9 21 21

F) 
formatC(pi,format="f",digits=22)
#[1] "3.1415926535897931159980"
 formatC(sqrt(2),format="f",digits=22)
#[1] "1.4142135623730951454746"

 x <- c("3.14", "3.142", "3.1400", "123456.123456789", 
"123456789.123456789",formatC(pi,format="f",digits=22),formatC(sqrt(2),format="f",digits=22))
 decimalnumcount(x)
#[1]  2  3  2  9  9 21 22


G)
#  formatC() didn't show the limitations of print() 
 print(sqrt(2),22)
#[1] 1.414213562373095145475

print(sqrt(2),35)
#Error in print.default(sqrt(2), 35) : invalid 'digits' argument

formatC(sqrt(2),35)
#[1] "1.4142135623730951454746218587388285"
or,
formatC(sqrt(2),format="f",digits=35)
#[1] "1.41421356237309514547462185873882845"


#using >22

x <- c("3.14", "3.142", "3.1400", "123456.123456789", 
"123456789.123456789",formatC(pi,format="f",digits=35),formatC(sqrt(2),format="f",digits=50))
 decimalnumcount(x)
#[1]  2  3  2  9  9 35 50




So, I guess it will be better to deal with character strings rather than using 
as.character.
A.K.




- Original Message -
From: "ted.hard...@wlandres.net" 
To: r-help@r-project.org
Cc: Martin Ivanov 
Sent: Saturday, July 7, 2012 8:12 AM
Subject: Re: [R] number of decimal places in a number?

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):
  f(123456789.123456789)
  # [1] 7

[B] (the "gsub()" method)
  nchar(gsub("(.*\\.)|([0]*$)", "", as.character(123456789.123456789)))
  # [1] 6

Now look at:

[C] (what as.character() does to 123456789.123456789)
  as.character(123456789.123456789)
  # [1] "123456789.123457"

[D] ("22" is the maximum number of decimal digits for print())
  print(123456789.123456789,22)
  # [1] 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
is about the limit (depending on the magnitude of the number)
that R can hold internally; this agrees with [A].

Note the difference between

[D] ("22" is the maximum number of decimal digits for print())
  print(123456789.123456789,22)
  # [1] 123456789.1234568

[E] (similar, but with a different magnitude)
  print(923456789.123456789,22)
  # [1] 923456789.123457

(compare with [C]).

So, clearly, there is potential uncertainty in the ouput
from either method, but perhaps there is somewhat more
uncertainty with the "gsub()" method.

Also, another nasty little trap with "gsub()":

[F] (my method)
  f(0.012345)
  # [1] 10

[G] ("gsub()" method)
  nchar(gsub("(.*\\.)|([0]*$)", "", as.character(0.012345)))
  # [1] 8

which arises b

Re: [R] number of decimal places in a number?

2012-07-07 Thread Martin Ivanov
 Dear Mr Harding,

Thank You very much for Your responsiveness.

 >There would seem to be no clean general solution to this
 >question. An important issue would be: What use do you
 >want to put the result to?
 
I need this trick for the following task.
I am writing a function which has to determine the bounding box for a 
spatial data set. The bounding box is a matrix(c(minLon minLat, maxLon, 
maxLat)).
I have the longitudes (lon) and latitudes (lat), and I have a resolution (r), 
for example 
r = 0.004. The bounding box must have the same number of digits as resolution. 
So I first have to truncate min(lon) and min(lat) to 3 decimal places,
then take the ceiling of max(lat)*10^3 and max(lon)*10^3 divided by 10^3. So I 
have the 
maximal interval with resolution r for each variable (lat or lon). Then I have 
to determine
the number of cells in each direction, which I take as 
ceiling((maxLat-minLat)/r) and
ceiling((maxLon-minLon)/r). Here is an example of my code:

 # get the first n digits from a number
truncf <- function(x, digits) {
 # some control:
 for(i in c("x", "digits")) if(!(is.numeric(get(i)) && length(get(i)) == 1)) 
stop(i, " in truncatef must be a  numeric scalar!");
 ## make sure that digits is an integer:
 if(as.integer(digits) - digits) stop("Please provide an integer digits to 
truncf!");

 x <- trunc(x*10^digits)/10^digits;
 x;
}
 for(i in 0:5) if(!(resolution*10^i - as.integer(resolution*10^i))) break;
 lonMin <- truncf(x=min(lon), digits=i); lonMax <- 
ceiling(x=max(lon)*10^i)/10^i;
 latMin <- truncf(min(lat), digits=i); latMax <- ceiling(x=max(lat)*10^i)/10^i;
 cells.dim <- ceiling(c(lonMax - lonMin, latMax - latMin)/resolution);
 
 
I hope this sheds more light on my issue.

Best regards,
Martin

-
Гражданска отговорност – Цените на компаниите
http://www.sdi.bg/onlineInsurance/?utm_source=gbg&utm_medium=txtLink&utm_content=home

__
R-help@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.


Re: [R] number of decimal places in a number?

2012-07-07 Thread Ted Harding
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):
  f(123456789.123456789)
  # [1] 7

[B] (the "gsub()" method)
  nchar(gsub("(.*\\.)|([0]*$)", "", as.character(123456789.123456789)))
  # [1] 6

Now look at:

[C] (what as.character() does to 123456789.123456789)
  as.character(123456789.123456789)
  # [1] "123456789.123457"

[D] ("22" is the maximum number of decimal digits for print())
  print(123456789.123456789,22)
  # [1] 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
is about the limit (depending on the magnitude of the number)
that R can hold internally; this agrees with [A].

Note the difference between

[D] ("22" is the maximum number of decimal digits for print())
  print(123456789.123456789,22)
  # [1] 123456789.1234568

[E] (similar, but with a different magnitude)
  print(923456789.123456789,22)
  # [1] 923456789.123457

(compare with [C]).

So, clearly, there is potential uncertainty in the ouput
from either method, but perhaps there is somewhat more
uncertainty with the "gsub()" method.

Also, another nasty little trap with "gsub()":

[F] (my method)
  f(0.012345)
  # [1] 10

[G] ("gsub()" method)
  nchar(gsub("(.*\\.)|([0]*$)", "", as.character(0.012345)))
  # [1] 8

which arises because:

  as.character(0.012345)
  # [1] "1.2345e-06"

There would seem to be no clean general solution to this
question. An important issue would be: What use do you
want to put the result to?

If there is something in the logic of your application
which depends critically on the numbers of decimal places
in its numerical input, then the final result could be
completey wrong because of these uncertainties.

In such a case, it might be best to force initial input
to be of character format. For example, if reading numerical
data into a dataframe from (say) a CSV file, then the option

Data <- read.csv("datafile.csv",colClasses="character")

(or similar) would convert all numerical data into the equivalent
character formats. Then Joshua's "gsub()" method would always
give exactly the right result when applied to these character
strings. Then, having got that out of the way, you can convert
the character strings into numeric (to within the precision
that R will allow).

However, if something in the logic depends critically on the
numbers of "decimal places" in numbers computed internally by R,
then I think the case is hopeless!

Ted.

On 07-Jul-2012 10:44:55 Joshua Wiley wrote:
> Hi Martin,
> 
> Ted is spot on about the binary representation.  A very different
> approach from his would be to convert to character and use regular
> expressions:
> 
>## the example numbers in a vector
> x <- c(3.14, 3.142, 3.1400, 123456.123456789, 123456789.123456789, pi,
> sqrt(2))
> 
> nchar(gsub("(.*\\.)|([0]*$)", "", as.character(x)))
> 
> which for me returns:
> [1]  2  3  2  9  6 14 13
> 
> an advantage of this approach is that for numbers like
> 123456789.123456789, although R cannot represent it properly as a
> binary number, the character string is totally fine.
> 
> nchar(gsub("(.*\\.)|([0]*$)", "", "123456789.123456789"))
> 
> returns 9
> 
> Essentially the expression looks for anything (the period) zero or
> more times (the *) followed by an actual period (the \\.) OR 0
> repeated zero or more times at the end of the string, and replaces all
> of those with nothing (the "") and then returns the result, the number
> of characters of which is counted by nchar()
> 
> See ?regex for details
> 
> Cheers,
> 
> Josh
> 
> On Sat, Jul 7, 2012 at 3:04 AM, Ted Harding  wrote:
>> On 07-Jul-2012 08:52:35 Martin Ivanov wrote:
>>>  Dear R users,
>>>
>>> I need a function that gets a number and returns its number of
>>> actual decimal places.
>>> For example f(3.14) should return 2, f(3.142) should return 3,
>>> f(3.1400) should also return 2 and so on. Is such function already
>>> available in R? If not, could you give me a hint how to achieve that?
>>>
>>> Many thanks in advance.
>>
>> I'm not aware of such a function in R. In any case, it will be
>> a tricky question to solve in full generality, since R stores
>> numbers internally in a binary representation and the exact
>> conversion of this representation to a decimal number may not
>> match the exact value of the decimal representation of the
>> original number.
>>
>> In particular, a number entered as a decimal representation
>> from the keyboard, or read as such from a text fi

Re: [R] number of decimal places in a number?

2012-07-07 Thread Joshua Wiley
Hi Martin,

Ted is spot on about the binary representation.  A very different
approach from his would be to convert to character and use regular
expressions:

## the example numbers in a vector
x <- c(3.14, 3.142, 3.1400, 123456.123456789, 123456789.123456789, pi, sqrt(2))

nchar(gsub("(.*\\.)|([0]*$)", "", as.character(x)))

which for me returns:
[1]  2  3  2  9  6 14 13

an advantage of this approach is that for numbers like
123456789.123456789, although R cannot represent it properly as a
binary number, the character string is totally fine.

nchar(gsub("(.*\\.)|([0]*$)", "", "123456789.123456789"))

returns 9

Essentially the expression looks for anything (the period) zero or
more times (the *) followed by an actual period (the \\.) OR 0
repeated zero or more times at the end of the string, and replaces all
of those with nothing (the "") and then returns the result, the number
of characters of which is counted by nchar()

See ?regex for details

Cheers,

Josh

On Sat, Jul 7, 2012 at 3:04 AM, Ted Harding  wrote:
> On 07-Jul-2012 08:52:35 Martin Ivanov wrote:
>>  Dear R users,
>>
>> I need a function that gets a number and returns its number of
>> actual decimal places.
>> For example f(3.14) should return 2, f(3.142) should return 3,
>> f(3.1400) should also return 2 and so on. Is such function already
>> available in R? If not, could you give me a hint how to achieve that?
>>
>> Many thanks in advance.
>
> I'm not aware of such a function in R. In any case, it will be
> a tricky question to solve in full generality, since R stores
> numbers internally in a binary representation and the exact
> conversion of this representation to a decimal number may not
> match the exact value of the decimal representation of the
> original number.
>
> In particular, a number entered as a decimal representation
> from the keyboard, or read as such from a text file, may not
> be exactly matched by the internal representation in R.
>
> However, that said, the following function definition seems to
> do what you are asking for, for cases such as you list:
>
> f<-function(x) {min(which( x*10^(0:20)==floor(x*10^(0:20)) )) - 1}
>
>   f(3.14)
>   # [1] 2
>   f(3.142)
>   # [1] 3
>   f(3.1400)
>   # [1] 2
>
>
>
> Note, however:
>
>   f(123456.123456789)
>   # [1] 9
>
>   f(123456789.123456789)
>   #[1] 7
>
> (a consequence of the fact that R does not have enough binary
> digits in its binary representation to accommodate the precision
> in all the decimal digits of 123456789.123456789 -- not that it
> can do that exactly anyway in binary, no matter how many binary
> digits it had available).
>
> Similarly:
>
>   f(pi)
>   # [1] 15
>   f(sqrt(2))
>   # [1] 16
>
> which is a consequence of the fact that 2 < pi < 4, while
> 1 < sqrt(2) < 2, so the binary representation of pi needs
> 1 more binary digit for its integer part than sqrt(2) does,
> which it therefore has to "steal" from the fractional part.
>
> Hoping this helps,
> Ted.
>
> -
> E-Mail: (Ted Harding) 
> Date: 07-Jul-2012  Time: 11:04:26
> This message was sent by XFMail
>
> __
> R-help@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.



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
Programmer Analyst II, Statistical Consulting Group
University of California, Los Angeles
https://joshuawiley.com/

__
R-help@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.


Re: [R] number of decimal places in a number?

2012-07-07 Thread Ted Harding
On 07-Jul-2012 08:52:35 Martin Ivanov wrote:
>  Dear R users,
> 
> I need a function that gets a number and returns its number of
> actual decimal places.
> For example f(3.14) should return 2, f(3.142) should return 3,
> f(3.1400) should also return 2 and so on. Is such function already
> available in R? If not, could you give me a hint how to achieve that?
> 
> Many thanks in advance.

I'm not aware of such a function in R. In any case, it will be
a tricky question to solve in full generality, since R stores
numbers internally in a binary representation and the exact
conversion of this representation to a decimal number may not
match the exact value of the decimal representation of the
original number.

In particular, a number entered as a decimal representation
from the keyboard, or read as such from a text file, may not
be exactly matched by the internal representation in R.

However, that said, the following function definition seems to
do what you are asking for, for cases such as you list:

f<-function(x) {min(which( x*10^(0:20)==floor(x*10^(0:20)) )) - 1}

  f(3.14)
  # [1] 2
  f(3.142)
  # [1] 3
  f(3.1400)
  # [1] 2



Note, however:

  f(123456.123456789)
  # [1] 9

  f(123456789.123456789)
  #[1] 7

(a consequence of the fact that R does not have enough binary
digits in its binary representation to accommodate the precision
in all the decimal digits of 123456789.123456789 -- not that it
can do that exactly anyway in binary, no matter how many binary
digits it had available).

Similarly:

  f(pi)
  # [1] 15
  f(sqrt(2))
  # [1] 16

which is a consequence of the fact that 2 < pi < 4, while
1 < sqrt(2) < 2, so the binary representation of pi needs
1 more binary digit for its integer part than sqrt(2) does,
which it therefore has to "steal" from the fractional part.

Hoping this helps,
Ted.

-
E-Mail: (Ted Harding) 
Date: 07-Jul-2012  Time: 11:04:26
This message was sent by XFMail

__
R-help@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.


[R] number of decimal places in a number?

2012-07-07 Thread Martin Ivanov
 Dear R users,

I need a function that gets a number and returns its number of actual decimal 
places.
For example f(3.14) should return 2, f(3.142) should return 3, f(3.1400) should 
also return 2
and so on. Is such function already available in R? If not, could you give me a 
hint how to achieve that?

Many thanks in advance.

-
Гражданска отговорност – Цените на компаниите
http://www.sdi.bg/onlineInsurance/?utm_source=gbg&utm_medium=txtLink&utm_content=home

__
R-help@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.