[R] float and double precision with C code

From: JS Ubei <jsubei_at_yahoo.fr>
Date: Thu, 17 Jul 2008 12:47:41 +0000 (GMT)


Hi all,

There is a mistake for wich I need your ligths :

///////////////////////////////////////

I have a small C code :

SEXP testData()
{

    SEXP result;
    void * rans;
    float * my_data;
    int my_data_length;

    my_data_length = 2;
    my_data = new float[my_data_length];     

    my_data[0] = 29.958334;
    my_data[1] = 29.875;     

    PROTECT(result = allocVector(REALSXP, my_data_length));     rans = (void *)REAL(result);

    for(int i=0; i < my_data_length; i++) ((double *)rans)[i] = (double)(my_data[i]);

Rprintf("C value #1 : %f\n", ((double *)rans)[0]); Rprintf("C value #2 : %f\n", ((double *)rans)[1]);

    delete(my_data);

    UNPROTECT(1);
    return(result);
}

///////////////////////////////////////

And the R corresponding function :

testData <- function()
{

        result <- .Call("testData", PACKAGE="my_package") print(paste("R value #1 :", result[1]))
print(paste("R value #2 :", result[2]))

        return(result)
}

///////////////////////////////////////

And in R console, after compilation :

> my_result <- testData()

C value #1 : 29.958334
C value #2 : 29.875000
[1] "R value #1 : 29.9583339691162"
[1] "R value #2 : 29.875"

> my_result[1] == 29.958334

[1] FALSE ???

How can I do to conserve my values ?

Regards,



e http://mail.yahoo.fr

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 Thu 17 Jul 2008 - 12:49:49 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 Thu 17 Jul 2008 - 14:31:25 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.

list of date sections of archive