[ create a new paste ] login | about

Link: http://codepad.org/SbHEjl1F    [ raw code | output | fork ]

AaronMiller - C++, pasted on Aug 18:
#include <cmath>
#include <cstdio>
#include <cstdlib>

inline float clamp(float x, float lo, float hi) {
  x = (x + hi - fabsf(x - hi))*0.5f;
  x = (x + lo + fabsf(x - lo))*0.5f;
  return x;
}

void test(float x, float lo, float hi) {
  printf("%.4f:[%.4f .. %.4f] -> %.4f\n", x, lo, hi, clamp(x, lo, hi));
}

int main() {
  test( 0.0f, -1.0f, +1.0f);
  test( 0.8f, -1.0f, +1.0f);
  test(-0.8f, -1.0f, +1.0f);
  test(-2.0f, -1.0f, +1.0f);
  test(+2.0f, -1.0f, +1.0f);

  return EXIT_SUCCESS;
}


Output:
1
2
3
4
5
0.0000:[-1.0000 .. 1.0000] -> 0.0000
0.8000:[-1.0000 .. 1.0000] -> 0.8000
-0.8000:[-1.0000 .. 1.0000] -> -0.8000
-2.0000:[-1.0000 .. 1.0000] -> -1.0000
2.0000:[-1.0000 .. 1.0000] -> 1.0000


Create a new paste based on this one


Comments: