fmod.c 627 B

12345678910111213141516171819202122232425262728293031323334
  1. /* fmod function */
  2. /* Author Robert R. Hall (hall@crach.cts.com) */
  3. /* $Id$ */
  4. #include <math.h>
  5. #include <errno.h>
  6. double
  7. (fmod)(double x, double y)
  8. { /* compute fmod(x, y) */
  9. double t;
  10. int n, neg;
  11. int ychar, xchar;
  12. if (y == 0.0) {
  13. errno = EDOM;
  14. return 0.0;
  15. }
  16. /* fmod(finite, finite) */
  17. if (y < 0.0) y = -y;
  18. if (x < 0.0) x = -x, neg = 1;
  19. else neg = 0;
  20. t = frexp(y, &ychar);
  21. /* substract |y| until |x| < |y| */
  22. t = frexp(x, &xchar);
  23. for (n = xchar - ychar; 0 <= n; --n) {
  24. /* try to substract |y|*2^n */
  25. t = ldexp(y, n);
  26. if (t <= x) x -= t;
  27. }
  28. return (neg ? -x : x);
  29. }