Dear all,
I want to compute the standard deviation. First I compute the variance with avesq-ave^2, then compute its square root. The variance can be negative if it is very small and near zero, like -2e-17
. So I want to set it to zero if it is negative. In lammps source code, I could use MAX(variance, 0)
to do the limitation. But in lammps script, there seems to be only a ternary function in the variable that can do this. So I try variable Std equal ternary(v_Var>0,sqrt(v_Var),0)
. Then I encountered this error:
ERROR on proc 0: Variable Std: Sqrt of negative value in variable formula
Why did lammps compute the sqrt of a negative value even if I specify the condition? With this question, I check the source code.
No matter whether arg2
and arg3
are valid, they will always be computed. In C++, the ternary opeartor has short-circuit mechanism, i.e., only one of arg2
and arg3
is calculated but not all of them.
In some cases, only one of the args is valid and computing the invalid value will yield errors. For example, only compute sqrt(x)
when x>=0, only compute a/b when abs(b)>1e-15, etc.
I don’t know if it is appropriate if the source code is modified as follows:
if (tree->type == TERNARY) {
arg1 = collapse_tree(tree->first);
if (tree->first->type != VALUE) return 0.0;
tree->type = VALUE;
if (arg1) tree->value = collapse_tree(tree->second);
else tree->value = collapse_tree(tree->extra[0]);
return tree->value;
}