I was hoping someone could evaluate this code in which I am seeking to create a Random Variable Z using a Uniform Variable U and numerous Constant variables within a summation.
I have U(0,1) and constants a0=2.51..., a2=0.01, and b0=1...b3=0.0013.
and based on if U is > or < than 0.5 we get either Z1 or Z2 in return. My code is below!
w <- (sqrt((-2)*(log(U))))
a[1] <- 2.515517
a[2] <- 0.802853
a[3] <- 0.010328
b[1] <- 1
b[2] <- 1.432788
b[3] <- 0.189269
b[4] <- 0.001308
U <- runif(1)
if(U<=0.5) {
print(ZOne <- ((-w)+((sum(((a[i])*(w^[i])), i=1, 3))/(sum(((b[j])*(w^[j])), j=1, 4)))))
} else {
print(ZTwo <- ((1)-(((-w)+((sum(((a[i])*(w^[i])), i=1, 3))/(sum(((b[j])*(w^[j])), j=1, 4)))))))
}
Hope this makes sense, just for reference ZOne = , when U=<0.5.
ZTwo is (1-ZOne), when U>=0.5.
If you need any clarification please just let me know. Thank you!
*PS, I somehow need to create 1000 of these variables (Z), and figured I would just use the replicate for that.
a <- numeric(3)
b <- numeric(4)
a[1] <- 2.515517
a[2] <- 0.802853
a[3] <- 0.010328
b[1] <- 1
b[2] <- 1.432788
b[3] <- 0.189269
b[4] <- 0.001308
U <- runif(1)
# You can't use U before it exists!
w <- (sqrt((-2)*(log(U))))
# Here assuming w^2 in your equation is w * w etc.
# if not, remove ^(1 : length(a)) and ^(1 : length(b))
ZOne <- (-w) + sum(a * w^(1 : length(a)))/sum(b * w^(1 : length(b)))
if (U<=0.5) {
print(ZOne)
} else {
print(ZTwo <- 1 - ZOne)
}
This seems to be what you are trying to do:
Z <- function(){
w <- sqrt(-2*log(runif(1)))
a <- c(2.515517, 0.802853, 0.010328)
b <- c(1, 1.432788, 0.189269,0.001308)
ZOne <- -w+sum(a*w^(1:3))/sum(b*w^(1:4))
ZTwo <- 1 - ZOne
if(runif(1)<=0.5) {
Zval <- ZOne
} else {
Zval <- ZTwo
}
Zval
}
R operates on whole vectors. Using indices (i,j) is frequently a sign of poor design. Perhaps you might want to spend a certain amount of time reading a tutorial on R programming. By making it a function, you can use Z() to create random variates at will. E.g. something like replicate(1000,Z()) will create 1000 such values.
Related
I try to calculate the value for the following equation in R.
I have the dataset and the value for each corresponding F_x, F_{x+1}...
However, as both Q and s have too many values, I am considering write a loop in loop. It's bit confused. As a loop for Q seems conflicting as the loop for s
But if I write loop as below, seems like I need to by hand calculate Q 100 times to get all of the answer. Also my loop seems to be wrong...How can I fix this problem? Thank you so much
Y <- function(x,s, Q){
n <- length(s-x)-1
Q <- c(1:100)
for(s in seq(1:n)){
Y[s] <- sum(s*Q[s]*cumprod(Fx[1:s]))
}
return(Y)
}
I am not sure if the code below reaches your objective
Y <- function(x,s) {
Q <- 1:100
S <- 1:(s-x)
outer(Q,S,FUN = function(q,s) q * sum(c(1:s) * cumprod(Fx[1:s])))
}
for loop version
Y <- function(x,s) {
nr <- 100
nc <- s-x
y <- matrix(nr*nc,nrow = nr)
for (Q in 1:nr) {
for (S in 1:nc) {
y[Q,S] <- Q * sum(c(1:S) * cumprod(Fx[1:S]))
}
}
y
}
So I've been trying to (manually) implement the Cooley-Turkey FFT algorithm in R (for Inputs with size N=n^2). I tried:
myfft <- function(s){
N <- length(s)
if (N != 1){
s[1:(N/2)] <- myfft(s[(1:(N/2))*2-1])
s[(N/2+1):N] <- myfft(s[(1:(N/2))*2])
for (k in 1:(N/2)){
t <- s[k]
s[k] <- t + exp(-1i*2*pi*(k-1)/N) * s[k+N/2]
s[k+N/2] <- t - exp(-1i*2*pi*(k-1)/N) * s[k+N/2]
}
}
s
}
This compiles, but for n>1, N=2^n it does not compute the right values. I implemented a DFT-function and used the fft() function to compare, both compute, when normalized, give the same values, but seem to disagree with my algorithm above.
If anyone feels interested and sees where I went wrong, help would be greatly appreciated, I'm going mad searching for the mistake and am starting to question, if I even ever understood this FFT algorithm.
UPDATE: I fixed it, I'm not 100% sure where the problem exactly was, but here is the working implementation:
myfft <- function(s){
N <- length(s)
if (N != 1){
t <- s
t[1:(N/2)] <- myfft(s[(1:(N/2))*2-1]) # 1 3 5 7 ...
t[(N/2+1):N] <- myfft(s[(1:(N/2))*2]) # 2 4 6 8 ...
s[1:(N/2)] <- t[1:(N/2)] + exp(-1i*2*pi*(0:(N/2-1))/N) * t[(N/2+1):N]
s[(N/2+1):N] <- t[1:(N/2)] - exp(-1i*2*pi*(0:(N/2-1))/N) * t[(N/2+1):N]
}
return(s)
}
The problem was with the following line
s[1:(N/2)] <- myfft(s[(1:(N/2))*2-1])
which was overwriting part of the untransformed values that were needed on the subsequent line:
s[(N/2+1):N] <- myfft(s[(1:(N/2))*2])
For example, when N=4, the second call to myfft uses s[2] and s[4], but the assignment from the first call to myfft writes into s[1] and s[2] (thus overwriting the required original value in s[2]).
Your solution of copying the entire array prevents this overwrite.
An alternate solution commonly used is to copy the even and odd parts separately:
myfft <- function(s){
N <- length(s)
if (N != 1){
odd <- s[(1:(N/2))*2-1]
even <- s[(1:(N/2))*2]
s[1:(N/2)] <- myfft(odd)
s[(N/2+1):N] <- myfft(even)
s[1:(N/2)] <- t[1:(N/2)] + exp(-1i*2*pi*(0:(N/2-1))/N) * t[(N/2+1):N]
s[(N/2+1):N] <- t[1:(N/2)] - exp(-1i*2*pi*(0:(N/2-1))/N) * t[(N/2+1):N]
}
return(s)
}
I am re-writting an algorithm I did in C++ in R for practice called the Finite Difference Method. I am pretty new with R so I don't know all the rules regarding vector/matrix multiplication. For some reason I am getting a non-conformable arguments error when I do this:
ST_u <- matrix(0,M,1)
ST_l <- matrix(0,M,1)
for(i in 1:M){
Z <- matrix(gaussian_box_muller(i),M,1)
ST_u[i] <- (S0 + delta_S)*exp((r - (sigma*sigma)/(2.0))*T + sigma*sqrt(T)%*%Z)
ST_l[i] <- (S0 - delta_S)*exp((r - (sigma*sigma)/(2.0))*T + sigma*sqrt(T)%*%Z)
}
I get this error:
Error in sqrt(T) %*% Z : non-conformable arguments
Here is my whole code:
gaussian_box_muller <- function(n){
theta <- runif(n, 0, 2 * pi)
rsq <- rexp(n, 0.5)
x <- sqrt(rsq) * cos(theta)
return(x)
}
d_j <- function(j, S, K, r, v,T) {
return ((log(S/K) + (r + (-1^(j-1))*0.5*v*v)*T)/(v*(T^0.5)))
}
call_delta <- function(S,K,r,v,T){
return (S * dnorm(d_j(1, S, K, r, v, T))-K*exp(-r*T) * dnorm(d_j(2, S, K, r, v, T)))
}
Finite_Difference <- function(S0,K,r,sigma,T,M,delta_S){
ST_u <- matrix(0,M,1)
ST_l <- matrix(0,M,1)
for(i in 1:M){
Z <- matrix(gaussian_box_muller(i),M,1)
ST_u[i] <- (S0 + delta_S)*exp((r - (sigma*sigma)/(2.0))*T + sigma*sqrt(T)%*%Z)
ST_l[i] <- (S0 - delta_S)*exp((r - (sigma*sigma)/(2.0))*T + sigma*sqrt(T)%*%Z)
}
Delta <- matrix(0,M,1)
totDelta <- 0
for(i in 1:M){
if(ST_u[i] - K > 0 && ST_l[i] - K > 0){
Delta[i] <- ((ST_u[i] - K) - (ST_l[i] - K))/(2*delta_S)
}else{
Delta <- 0
}
totDelta = totDelta + exp(-r*T)*Delta[i]
}
totDelta <- totDelta * 1/M
Var <- 0
for(i in 1:M){
Var = Var + (Delta[i] - totDelta)^2
}
Var = Var*1/M
cat("The Finite Difference Delta is : ", totDelta)
call_Delta_a <- call_delta(S,K,r,sigma,T)
bias <- abs(call_Delta_a - totDelta)
cat("The bias is: ", bias)
cat("The Variance of the Finite Difference method is: ", Var)
MSE <- bias*bias + Var
cat("The marginal squared error is thus: ", MSE)
}
S0 <- 100.0
delta_S <- 0.001
K <- 100.0
r <- 0.05
sigma <- 0.2
T <- 1.0
M <- 10
result1 <- Finite_Difference(S0,K,r,sigma,T,M,delta_S)
I can't seem to figure out the problem, any suggestions would be greatly appreciated.
In R, the %*% operator is reserved for multiplying two conformable matrices. As one special case, you can also use it to multiply a vector by a matrix (or vice versa), if the vector can be treated as a row or column vector that conforms to the matrix; as a second special case, it can be used to multiply two vectors to calculate their inner product.
However, one thing it cannot do is perform scalar multipliciation. Scalar multiplication of vectors or matrices always uses the plain * operator. Specifically, in the expression sqrt(T) %*% Z, the first term sqrt(T) is a scalar, and the second Z is a matrix. If what you intend to do here is multiply the matrix Z by the scalar sqrt(T), then this should just be written sqrt(T) * Z.
When I made this change, your program still didn't work because of another bug -- S is used but never defined -- but I don't understand your algorithm well enough to attempt a fix.
A few other comments on the program not directly related to your original question:
The first loop in Finite_Difference looks suspicious: guassian_box_muller(i) generates a vector of length i as i varies in the loop from 1 up to M, and forcing these vectors into a column matrix of length M to generate Z is probably not doing what you want. It will "reuse" the values in a cycle to populate the matrix. Try these to see what I mean:
matrix(gaussian_box_muller(1),10,1) # all one value
matrix(gaussian_box_muller(3),10,1) # cycle of three values
You also use loops in many places where R's vector operations would be easier to read and (typically) faster to execute. For example, your definition of Var is equivalent to:
Var <- sum((Delta - totDelta)^2)/M
and the definitions of Delta and totDelta could also be written in this simplified fashion.
I'd suggest Googling for "vector and matrix operations in r" or something similar and reading some tutorials. Vector arithmetic in particular is idiomatic R, and you'll want to learn it early and use it often.
You might find it helpful to consider the rnorm function to generate random Gaussians.
Happy R-ing!
I'm writing some code in R and I came across following problem:
Basically, I want to calculate a variable X[k], where X takes on values for each k, like this:
where A is a known variable which takes on different values for each index.
For the moment, I have something like this:
k <- NULL
X <- NULL
z<- 1: n
for (k in seq(along =z)){
for (j in seq (along = 1:k)){
X[k] = 1/k*sum(A[n-k]/A[n-j+1])
}
}
which can't be right. Any idea on how to fix this one?
As always, any help would be dearly appreciated.
Try this
# define A
A <- c(1,2,3,4)
n <- length(A)
z <- 1:n
#predefine X (don't worry, all values will be overwritten, but it will have the same length as A
X <- A
for(k in z){
for(j in 1:k){
X[k] = 1/k*sum(A[n-k]/A[n-j+1])
}
}
You don't need to define z, it is only used inside the for. In this case, do for(k in 1:n){
As
You can do the following
set.seed(42)
A <- rnorm(10)
k <- sample(length(A), 4)
calc_x <- function(A, k){
n <- length(A)
c_sum <- cumsum(1/rev(A)[1:max(k)])
A[n-k]/k * c_sum[k]
}
calc_x(A,k)
what returns:
[1] 0.07775603 2.35789999 -0.45393983 0.13323284
I have an exercise to do where I have to run the following AR(1) model:
xi =c+φxi−1+ηi (i=1,...,T)
I know that ni ~ N(0,1) ; x0 ~ N(c/(1-φ),1/(1-φˆ2)); c= 2 ; φ = 0.6
I am trying to do a for loop. My code is the following:
n <- rnorm(T, 0, 1)
c <- 2
phi <- 0.6
x_0 <- rnorm(1,c/(1-phi), 1/(1-phi**2))
v <- vector("numeric", 0)
#for (i in 2:T){
name <- paste("x", i, sep="_")
v <- c(v,name)
v[1] <- c + phi*x_0 + n[1]
v[i] <- c + phi*v[i-1] + n[i]
}
However, I keep getting this error:
Error in phi * v[i - 1] : non-numeric argument to binary operator
I understand what this error is, but I can't find any solutions to solve it. Could someone please enlighten me? How could I assign numeric values to the name vector?
Thank you!
You're defining v as a numeric vector, but then v <- c(v, name) turns v into a character vector since name is character. That's what's causing the error.
If I'm not mistaken, your intent is to assign names to the values in a numeric vector. That's fine, you just need a different approach.
n <- rnorm(t)
c <- 2
phi <- 0.6
x_0 <- rnorm(1, c/(1-phi), 1/(1-phi^2))
v <- c + phi*x_0 + n[1]
for (i in 2:t) {
v[i] <- c + phi*v[i-1] + n[i]
}
names(v) <- paste("x", 1:t, sep="_")
Vectors in R don't have a static size; they're dynamically resized as needed. So even though we're initializing v with a scalar value, it grows to fit each new value in the loop.
The final step is to give v a list of names. This can be accomplished using names(v) <-. Take a look at v now--it has names!
And as an aside, since T is a synonym for TRUE in R, it's best not to use T as a variable name. Thus I've used t here instead.
I guess you seem to need the following. It'll produces 11 elements including the initial x value. You may exclude it later.
set.seed(1237)
t <- 10
n <- rnorm(t, 0, 1)
c <- 2
phi <- 0.6
x0 <- rnorm(1, c/(1-phi), 1/(1-phi**2))
v <- c(x0, rep(0, t))
for(i in 2:length(v)) {
v[i] <- c + phi * v[i-1] + n[i-1]
}
v
[1] 4.967833 4.535847 2.748292 2.792992 5.389548 6.173001 4.526824 3.790483 4.307981 5.442913 4.958193