Reputation: 105
I have this two functions:
Hwave_1 <- function(t) {
ifelse(0 <= t & t <= 1 / 2, t, ifelse(1 / 2 < t & t <= 1, 1 - t, 0))
}
HaarI <-function(m,k,t){
ifelse(t > 1 | t < 0, "HaarErrorTimes", 2^((-m)/2)*Hwave_1((2^m)*t-k))
}
I'm trying to create a function as in the image
where the Z_nj=rnorm(1)
I tried to do some naive things like
simul_weiner<-function(t,m){
for(i in 0:(2^m-1)){result<-sum(rnorm(1)*HaarI(m,i,t))}
ifelse(n=0,rnorm(1)*HaarI(0,0,t),result+rnorm(1)*HaarI(0,0,t))
}
but it clearly doesnt work because sum()
is summing every entry, I dont know if there exist a workaround or another sum function that can help me make the code work.
EDIT: Steps to reproduce
#create times vector
times<-seq(from=0, to=1,by=2^(-5))
#call the function on times with any m you choose, i choose 2 for simplicity
simul_weiner(times,2)
It should output a list with the same number repeating.
Upvotes: 0
Views: 56
Reputation: 160407
Looking at
for(i in 0:(2^m-1)){result<-sum(rnorm(1)*HaarI(m,i,t))}
Realize that before the for
loop runs, result
is undefined. When i
is 0 (first pass), it is defined as the singular value resulting from sum
. When i
is 1 (second pass), the value of result
is over-written with the singular value resulting from this call to sum
. Etc. When you finish your for
loop, result
contains the last sum
calculated.
Perhaps you should instead use
result <- sapply(0:(2^m-1), function(i) sum(rnorm(1)*HaarI(m,i,t)))
Next problem:
ifelse(n=0, ...)
That conditional is fundamentally broken. It is syntactically not an error, but it will always always always be false, because n=0
is an assignment, which in this case will invisibly return 0
, which is considered FALSE
for ifelse
. Furthermore, n
is undefined, so it should really be producing an error.
If n
is supposed to be m
, then ifelse
is not needed, as m
is length 1. The fact that it includes t
in it (with a length greater than 1 in your example) suggests that this is not the case.
If n
is a variable in the enclosing environment (not in this function), then ... don't do that. It's sloppy, not reproducible, breaks in unpredictable ways, difficult to troubleshoot, and condition enough for me to suspect any code using it.
Upvotes: 1