[R] floating point in single precision
Sebastian Gibb
lists at sebastiangibb.de
Sun Jun 27 21:22:52 CEST 2010
Am Sonntag, 27. Juni 2010, 08:39:10 schrieb Prof Brian Ripley:
> On Sun, 27 Jun 2010, Sebastian Gibb wrote:
> > Hello,
> >
> > is there a possibilty in R to convert numbers (double precision, 64bit)
> > into single precision ones (32bit).
> > I need that for compatibility reasons. Until now I call a C application
> > which casts a double to a float.
> >
> > float precision32(double value) {
> >
> > return (float)value;
> >
> > }
> >
> > But I want to use a R only method. What can I do?
>
> ?as.single
> ?writeBin
Thanks a lot for the hints.
I use the following code now:
### function double2singlePrecision
## wrapper function for .changePrecision(x, size=4)
##
double2singlePrecision <- function(x) {
stopifnot(is.double(x));
return(.changePrecision(x, size=4));
}
### function .changePrecision
## converts double values to double values in a given precision
## (only correctly working for cut a higher precision to a lower one; e.g.
## IEEE 754 double precision to IEEE 754 single precision)
##
.changePrecision <- function(x, size) {
# create a raw object to avoid direct file access
virtualCon <- raw();
# write binary data to raw object and change (mostly cut) precision to size
# size==4 # 32bit, single precision
# size==8 # 64bit, double precision
virtualCon <- writeBin(object=x, con=virtualCon, size=size);
# re-read data
x <- readBin(con=virtualCon, what=double(), size=size, n=length(x));
return(x);
}
Kind regards,
Sebastian
More information about the R-help
mailing list