# Avoid NANs by using an alternative calculation. Does it break the derivatives in sampling?

When starting the sampling I face some NaN exceptions due to `a` (or `b`) gets great. Thus
`square(a)` overflows. I overcome this problems by two branches, depending on the
value of the numbers. The value calculated remains the same, but the derivatives are different.

Question: Does this break the sampling process?

``````model {
real x;
a ~ exponential(10);
b ~ exponential(10);

if(a > 1.0e10 || b > 1.0e10)
x = exp(0.5 * log_sum_exp(2.0 * log(a), 2.0 * log(b));
else
x = sqrt(square(a) + square(b));
}
``````

And this the code, where I receive this errors.

``````  vector eigenvalues_2by2(vector sigma, real rho) {
if(!is_nan(sigma[1]) && !is_nan(sigma[2]) && !is_inf(sigma[1]) && !is_inf(sigma[2])
&& rho != 0.0 && sigma[1] > 1e-100 && sigma[2] > 1e-100 && sigma[1] < 1e10 && sigma[2] < 1e10) {
vector[2] EVa;
vector[2] sigma_sq = square(sigma);
real root = sqrt(sigma_quad[1] - 2 * sigma_sq[1] * sigma_sq[2] + 4 * square(rho) * sigma_sq[1] * sigma_sq[2] + sigma_quad[2]);
real b = sigma_sq[1] + sigma_sq[2];
EVa[1] = 0.5 * (b - root);
EVa[2] = 0.5 * (b + root);
return EVa;
} else {
matrix[2, 2] X;
X[1,1] = square(sigma[1]);
X[1,2] = sigma[1] * (sigma[2] * rho);
X[2,1] = X[1,2];
X[2,2] = square(sigma[2]);
return eigenvalues_sym(X);
}
}
}
``````

I don’t think the derivatives should be different. As long as a > 0 and b > 0, they are the same (maybe bound them a tiny bit away?). If the first one behaves better, why not just roll with that and skip the if?

Is it the model diagnosis derivatives that are different?

If `sigma` is a great number in initialization phase, then `sigma^4` in the code overflows and gets rejected. I recently receive a lot of additional messages like this: `Exception: weibull_lpdf: Random variable[3] is inf, but must be finite!` in CMDSTAN 2.18.1. I don’t understand why Stan samples NANs. If Stan being initialized [-2, 2] or was is normal(0, 2)?,