Calling a Fortran subroutine in R

Viewed 80

EDITED

I am trying to integrate R and Fortran, calling a Fortran subroutine in R. I'm new to Fortran, but I'm not new to R or to programming.

I wrote a subroutine in Fortran to calculate the sinc function, and I want to call it in R. This is the subroutine:

SUBROUTINE SINC(X,Y)
    IMPLICIT NONE
    DOUBLE PRECISION , INTENT(IN) :: X
    DOUBLE PRECISION , PARAMETER :: PI = 4.D0*ATAN(1.0)
    DOUBLE PRECISION , INTENT(OUT) :: Y
    
    IF(X == 0) THEN
        Y = 1
    ELSE
        Y = (SIN(PI*X))/(PI*X)
    END IF
END SUBROUTINE SINC

I wrote a Fortran code to test it, and it runs nicely.

PROGRAM DEMO
DOUBLE PRECISION A, B
PRINT *, "WHAT IS THE NUMBER YOU WANT TO SINC?"
READ *, A
CALL SINC(A, B)
PRINT *, "THE SINC IS", B
END PROGRAM DEMO

SUBROUTINE SINC(X,Y)
    IMPLICIT NONE
    DOUBLE PRECISION , INTENT(IN) :: X
    DOUBLE PRECISION , PARAMETER :: PI = 4.D0*ATAN(1.0)
    DOUBLE PRECISION , INTENT(OUT) :: Y
    
    IF(X == 0) THEN
        PRINT *, "X IS NULL"
        Y = 1
    ELSE
        PRINT *, "X IS NON NULL"
        Y = (SIN(PI*X))/(PI*X)
    END IF
END SUBROUTINE SINC

I compiled the subroutine (not the program) to a .dll file using the following command

R CMD SHLIB sinc.f95

If I defined my variables with REAL instead of DOUBLE PRECISION, when I ran it passing the parameter for Y, it basically returned me the parameter for Y I passed and I don't know why.

dyn.load("D:\\Fortran\\sinc.dll")
.Fortran("sinc", X=as.double(0), Y=as.double(1))

$X
[1] 0

$Y
[1] 1

The subroutine works perfectly fine for values that are non-integers, such as 1.1 or 2.5. However, when I try computing it for integer values, such as 1,2,3,4... the subroutine returns me -2.7827534378485793E-008, whereas in R i get 3.898043e-17. I know both are zeroes, but the precision is different in that case.

What am I doing wrong? How can I fix this to call my subroutine in R? I'm using gfortran as my compiler.

0 Answers
Related