Right—not if used to remove derivatives from an important calculation. For instance, you can’t do discrete sampling this way and get the right information flow.

You can simplify the code a bit with direct returns.

```
int bin_search(real x, int min_val, int max_val) {
if (min_val > x || max_val < x)
reject("require min < x < max, found min = ", min_val, "; max = ", max_val, "; x = ", x);
real y = round(x);
int range = max_val - min_val;
real mid_pt = min_val;
while (1) {
if (range == 0) return mid_pt;
range = (range + 1) / 2;
mid_pt += y > mid_pt ? range : -range;
}
}
```

The rounding makes the function platform specific, I’m afraid. I wrote a more general one of these recently that rounded to closest negative numbers, too.

This won’t quite work as written because Stan’s not clever enough (yet) to figure out that this function either loops infinitely or returns—it needs a final `return min_val`

after the loop to satisfy the compiler (we need to fix that—if the only way out of a loop is to return, it’s an OK final statement in a non-void function).

Unfortunately, if `y`

is an autodiff variable, all that arithmetic for `mid_pt`

gets added to the autodiff stack to no good end.