Skip to content

Troubles with the function rmultinom.c of the R's Random Number Generator

2 messages · Sophie Ancelet, Brian Ripley

#
Hi,

I'm simulating a Markov chain in Fortran interfaced with R-2.2.1 in order
to generate data according to a Markov Random Field called the Potts model. 

R Version: 
platform i686-pc-linux-gnu
arch     i686
os       linux-gnu
system   i686, linux-gnu
status
major    2
minor    2.1
year     2005
month    12
day      20
svn rev  36812




Each loop of my Fortran calls the function rmultinom.c of the R's Random
Number Generator through the wrapper:

#include <R.h>
#include <Rmath.h>
void F77_SUB(sarmultinom)(int n,
                          double* prob,
                          int K,
                          int* rN){
 rmultinom(n, prob, K, rN);}



My fortran program is:

subroutine testsarmultinom(n,prob,K,rN)
implicit none
integer n,K,rN(K)
double precision prob(K)

call rndstart()
call sarmultinom(n,prob,K,rN)
call rndend()
end


In order to understand better how the function rmultinom.c works, I have
written an R code which calls this fortran subroutine as follows:

system("R CMD SHLIB test-multinom.f wrapper.c")
dyn.load("~/Package/test/test-multinom.so")

n=1
prob=c(0.6,0.1,0.3)
K=3
rN=c(1,0,0)
res<- .Fortran("testsarmultinom",
               as.integer(n),
               as.double(prob),
               as.integer(K),
               as.integer(rN))


Unfortunately, I have some trouble with the results. First, this command
always returns 0 values. In other words, I always get:
[1] 0 0 0


Moreover, if I run this R code a second time, an error message appears:
Segmentation fault.

Has somebody ever used rmultinom.c and encountered these problems? My code
must be wrong but I don't know where. In this case, what is the correct way
to call the C function rmultinom.c?

Thanks in advance,

Sophie.




Sophie Ancelet
ENGREF
Laboratoire Grese 
19 avenue du Maine
75 732 Paris Cedex 15 
France
tel: 33 1 45 49 89 27
#
All arguments to functions called from C by Fortran are pointers
(or should be: yours are not).  The error is within your own code.

You don't want to call rndstart and rndend around every call, only before 
the first and after the last.

This is not the list for advice om mixed Fortran/C programming, though.
On Fri, 20 Jan 2006, Sophie Ancelet wrote: