Skip to content
Prev 13371 / 398502 Next

Using libRmath.a in Fortran?

On 6 Sep 2001, Peter Dalgaard BSA wrote:

            
Thanks to Peter, and also to Douglas Bates, who also gave hints to
how to solve the above-mentioned "naming issues": I came up with
the following program, which (seems to!?) work:

Fortran program (nrand.f) :
---------------------------
      program nrand

      implicit none

      integer first, second
      double precision frnorm, mean, sd, y

      first = 19609
      second = 10198

      call fsetseed(first, second)

      mean = 0.d0
      sd = 1.d0

      y = frnorm(mean, sd)
      write(*, '(/3(a, f6.3))') 'rnorm(', mean, ', ', sd, ') = ', y
C     Just to show that "y is random":
      y = frnorm(mean, sd)
      write(*, '(a, 9x, f6.3/)') 'another value: ', y

      end

And the  C  wrapper (frnorm.c) :
--------------------
#define MATHLIB_STANDALONE
#include <Rmath.h>      /* to define rnorm, etc */
#include <R_ext/RS.h>   /* to define F77_NAME */

double F77_NAME(frnorm)(double *mean, double *sd)
{
  return rnorm(*mean, *sd);
}

void F77_NAME(fsetseed)(int* one, int* two)
{
  set_seed( (unsigned int)(*one), (unsigned int)(*two) );
}

And the Makefile:
-----------------
OBJS = frnorm.o nrand.o

CFLAGS = -Wall -g -I/usr/local/lib/R/include
FFLAGS = -Wall -g -C

LIBS = -lRmath

nrand: $(OBJS)
	g77 -o nrand $(OBJS) $(LIBS)

%.o : %.f
	g77 $(FFLAGS) -c $<

%.o : %.c
	gcc $(CFLAGS) -c $<
--------------------------------------------------------------------

Is this correct? And is this a correct way of accessing the random
number generator? It is the line "A little care is needed to use the
random-number routines..." from the documentation that worries me a
little.

Thanks,

G?ran