I was reading this question, and thought about simulating the required quantity. The problem is as follows: If $A$ and $B$ are iid standard normal, what is $E(A^2|A+B)$? So I want to simulate $E(A^2|A+B)$. (for a chosen value of $A+B$)
I tried the following code to achieve this:
n <- 1000000
x <- 1 # the sum of A and B
A <- rnorm(n)
B <- rnorm(n)
sum_AB = A+B
estimate <- 1/sum(sum_AB==x) * sum( (A[sum_AB==x])^2 )
The problem is that there is almost always no value in sum_AB
which matches x
(across simulations). If I choose some element from sum_AB
, then it usually the only instance of its value in the vector.
In general, how can one tackle this problem and perform an accurate simulation to find an expectation of the given form? ($A$ and $B$ may not necessarily be normally distributed, or from the same distribution.)