R 教材:外部程式呼叫 R |
#include <R.h> #include <Rmath.h> void callR(){ int i; double mu, sigma, PHI_X, *X; mu = 0; sigma = 1; X = (double *) R_alloc(10, sizeof(double)); Rprintf("Before sort\n"); GetRNGstate(); for(i = 0; i < 10; i++){ X[i] = rnorm(mu, sigma); PHI_X = pnorm(X[i], mu, sigma, 1, 0); Rprintf("X: %f, PHI(X): %f\n", X[i], PHI_X); } PutRNGstate(); R_rsort(X, 10); Rprintf("After sort\n"); for(i = 0; i < 10; i++){ PHI_X = pnorm(X[i], mu, sigma, 1, 0); Rprintf("X: %f, PHI(X): %f\n", X[i], PHI_X); } } |
SHELL> gcc -shared -o callR.so callR.c -I/usr/lib/R/include/ -L/usr/lib/R/bin/ -lR | |
or | |
SHELL> R CMD SHLIB callR.c |
dyn.load("callR.so") set.seed(10) out <- .C("callR") dyn.unload("callR.so") |
Before sort X: 0.018746, PHI(X): 0.507478 X: -0.184253, PHI(X): 0.426908 X: -1.371331, PHI(X): 0.085136 X: -0.599168, PHI(X): 0.274531 X: 0.294545, PHI(X): 0.615829 X: 0.389794, PHI(X): 0.651656 X: -1.208076, PHI(X): 0.113509 X: -0.363676, PHI(X): 0.358050 X: -1.626673, PHI(X): 0.051903 X: -0.256478, PHI(X): 0.398791 After sort X: -1.626673, PHI(X): 0.051903 X: -1.371331, PHI(X): 0.085136 X: -1.208076, PHI(X): 0.113509 X: -0.599168, PHI(X): 0.274531 X: -0.363676, PHI(X): 0.358050 X: -0.256478, PHI(X): 0.398791 X: -0.184253, PHI(X): 0.426908 X: 0.018746, PHI(X): 0.507478 X: 0.294545, PHI(X): 0.615829 X: 0.389794, PHI(X): 0.651656 |
陳韋辰 (04/08/19) --- |