Most efficient/elegant way to clip a number?

前端 未结 11 722
予麋鹿
予麋鹿 2020-11-30 03:09

Given a real (n), a maximum value this real can be (upper), and a minimum value this real can be (lower), how can we most efficiently clip n, such that it remains between lo

11条回答
  •  [愿得一人]
    2020-11-30 03:23

    Inelegant, unsafe, costly but branchless:

    n= 0.5 * (n + lower + fabs(n - lower));
    n= 0.5 * (n + upper - fabs(upper - n));
    

提交回复
热议问题