First of all, I apologize for asking a silly question because I'm relatively new to R.
I've been trying for hours to fix this issue but I can't get it right. I've also tried to search some relevant topics on Google, but to no avail. I tried to create a function in R which can perform a Monte Carlo simulation which can't be properly handled in VBA. Here are the two functions I created:
ZoomRNG1 <- function(n,Px1,Px2,Py1,Py2)
{
sink("DataZoomRNG1.txt")
for(i in 1:n)
{
repeat
{
x = runif(1)
y = runif(1)
if(x > Px1 & x < Px2)
{
if(y > Py1 & y < Py2)
{
cat(i, x, y, "\n", sep="\t", append=TRUE);
break
}
}
}
}
sink()
}
and
ZoomRNG2 <- function(n,Px1,Px2,Py1,Py2)
{
logFile = "DataZoomRNG2.txt"
for(i in 1:n)
{
repeat
{
x = runif(1)
y = runif(1)
if(x > Px1 & x < Px2)
{
if(y > Py1 & y < Py2)
{
cat(i, x, y, file=logFile, append=TRUE, "\n", sep="\t");
break
}
}
}
}
}
Both functions work fine and the plot of ZoomRNG1 function outputs (1,000 data for each random variables x
and y
) in Excel is shown in the figure below:
But the problems are
- Both functions run relatively slow on my machine. OS: Windows 10 Pro 64-bit; System Model: HP Pro 3330 MT; Processor: Intel Core i3-2120 CPU @ 3.30GHz (4 CPUs); Memory: 4 GB.
- Some of their outputs' format are broken, for example
389 0.5067888 0.5064327
390 0.50462 0.5083072
391 0.5040369 0.5075297
392 0.5094 0.5064151
393 0.5068058 0.5041317
394 0.5073923 0.5002383
As one can see above, the formats of line 390 and 392 are broken (some of other lines are broken, too). How does one fix this issue? Also, is there a way to make both functions run faster? Something like (maybe?) writing the outputs of the function in array/ vector first and then exporting the result to an external file like I usually do when writing the program in VBA.