Reputation: 463
I'm trying to calculate derivatives of Gaussians in R and when I try to specify the mean and standard deviation, R seems to ignore this. For example, the following code works to plot a N(0,1) density and it's first and second derivative.
st_norm <- function(x) dnorm(x,0,1)
first_deriv <- function(x) {}
second_deriv <- function(x) {}
body(first_deriv) <- D(body(st_norm), 'x')
body(second_deriv) <- D(body(first_deriv), 'x')
curve(st_norm, -4, 4, ylim = c(-0.4, 0.4), col = 'blue')
curve(first_deriv, -4, 4, add = T, col = 'red')
curve(second_deriv, -4, 4, add = T, col = 'green')
abline(v=0, h=0)
and this produces the following plot:
But, suppose I wanted to do the exact same but to a N(2,2), then I change the code accordingly to:
different_norm <- function(x) dnorm(x,2,2)
different_first_deriv <- function(x) {}
different_second_deriv <- function(x) {}
body(different_first_deriv) <- D(body(different_norm), 'x')
body(different_second_deriv) <- D(body(different_first_deriv), 'x')
curve(different_norm, -4, 8, ylim = c(-0.4, 0.4), col = 'blue')
curve(different_first_deriv, -4, 8, add = T, col = 'red')
curve(different_second_deriv, -4, 8, add = T, col = 'green')
abline(v=0, h=0)
which produces this plot:
so you can see that it is taking the derivatives of a standard normal, not a N(2,2). If you print out the functions of first_deriv and different_first_deriv, they are equal, even though they are meant to be differentiating different functions.
Does anyone know how to fix this problem so I'm taking derivatives of the specified Gaussian distribution I want?
Upvotes: 0
Views: 3706
Reputation: 2717
It works if you use a different formula e.g. try this:
different_norm <- function(x, mean=2, sd=2) dnorm((x-mean)/sd, 0, 1)/sd
If you see the General normal distribution
section of https://en.wikipedia.org/wiki/Normal_distribution#Alternative_parameterizations then its a re-parameterisation of the standard normal.
I assume the issue is that the parameters mean
and sd
don't appear in the formula, and additional args from dnorm
aren't passing down for some reason
Upvotes: 1
Reputation: 463
You can just calculate the derivatives and write it out yourself
dnorm_deriv1 <- function(x, mean = 0, sd = 1) {
return(-((x-mean)/(sd^2))*dnorm(x, mean, sd))
}
dnorm_deriv2 <- function(x, mean = 0, sd = 1) {
return((((x-mean)^2) / (sd^4))*dnorm(x, mean, sd)
- (1/sd^2)*dnorm(x, mean, sd))
}
curve(dnorm, -4, 4, ylim = c(-0.4, 0.4), col = 'blue')
curve(dnorm_deriv1, -4, 4, add = T, col = 'red')
curve(dnorm_deriv2, -4, 4, add = T, col = ' green')
abline(v=0, h=0)
curve(dnorm(x, 2, 2), -4, 8, ylim = c(-0.1, 0.2), col = 'blue')
curve(dnorm_deriv1(x, 2, 2), -4, 8, add = T, col = 'red')
curve(dnorm_deriv2(x, 2, 2), -4, 8, add = T, col = ' green')
abline(v=2, h=0)
Upvotes: 0