/***************************************************************************** demo_var: test & demo for nwspgr, variables version integrate function using sparse grids and simulation *****************************************************************************/ clear local D = 10 // dimensions local maxk = 4 // max. accuracy level (pol. exactness wil be 2k-1) // true integral scalar trueval = (normal(.5)-.5)^`D' forvalues k=2/`maxk'{ quietly { // integration on sparse grids nwspgr, type(KPU) dim(`D') acc(`k') varn(x) varw(w) cap drop gD* lng gw forvalues d=1/`D'{ gen gD`d' = log( exp(-(x`d'/2)^2/2)/2/sqrt(2*_pi) ) } egen lng = rowtotal(gD*) gen gw = exp(lng) * w summarize gw local numnodes = r(N) scalar SGappr = r(sum) scalar SGerror = sqrt((SGappr - trueval)^2)/trueval // simulation with the same number of nodes, 1000 simulation repetitions scalar Simerror = 0 forvalues r=1/1000{ cap drop gD* lng gw forvalues d=1/`D'{ replace x`d' = uniform() if ~mi(w) gen gD`d' = log( exp(-(x`d'/2)^2/2)/2/sqrt(2*_pi) ) } egen lng = rowtotal(gD*) gen gw = exp(lng) quietly summarize gw scalar Simappr = r(mean) scalar Simerror = Simerror + (Simappr - trueval)^2 } scalar Simerror = sqrt(Simerror/1000)/trueval } dis "D=`D', k=`k' (nodes = `numnodes') SG error=" %8.5f SGerror ", Sim. error=" %8.5f Simerror }