go-matherr.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /* go-matherr.c -- a Go version of the matherr function.
  2. Copyright 2012 The Go Authors. All rights reserved.
  3. Use of this source code is governed by a BSD-style
  4. license that can be found in the LICENSE file. */
  5. /* The gccgo version of the math library calls libc functions. On
  6. some systems, such as Solaris, those functions will call matherr on
  7. exceptional conditions. This is a version of matherr appropriate
  8. for Go, one which returns the values that the Go math library
  9. expects. This is fine for pure Go programs. For mixed Go and C
  10. programs this will be problematic if the C programs themselves use
  11. matherr. Normally the C version of matherr will override this, and
  12. the Go code will just have to cope. If this turns out to be too
  13. problematic we can change to run pure Go code in the math library
  14. on systems that use matherr. */
  15. #include <math.h>
  16. #include <stdint.h>
  17. #include "config.h"
  18. #if defined(HAVE_MATHERR) && defined(HAVE_STRUCT_EXCEPTION)
  19. #define PI 3.14159265358979323846264338327950288419716939937510582097494459
  20. int
  21. matherr (struct exception* e)
  22. {
  23. const char *n;
  24. if (e->type != DOMAIN)
  25. return 0;
  26. n = e->name;
  27. if (__builtin_strcmp (n, "acos") == 0
  28. || __builtin_strcmp (n, "asin") == 0)
  29. e->retval = __builtin_nan ("");
  30. else if (__builtin_strcmp (n, "atan2") == 0)
  31. {
  32. if (e->arg1 == 0 && e->arg2 == 0)
  33. {
  34. double nz;
  35. nz = -0.0;
  36. if (__builtin_memcmp (&e->arg2, &nz, sizeof (double)) != 0)
  37. e->retval = e->arg1;
  38. else
  39. e->retval = copysign (PI, e->arg1);
  40. }
  41. else
  42. return 0;
  43. }
  44. else if (__builtin_strcmp (n, "log") == 0
  45. || __builtin_strcmp (n, "log10") == 0)
  46. e->retval = __builtin_nan ("");
  47. else if (__builtin_strcmp (n, "pow") == 0)
  48. {
  49. if (e->arg1 < 0)
  50. e->retval = __builtin_nan ("");
  51. else if (e->arg1 == 0 && e->arg2 == 0)
  52. e->retval = 1.0;
  53. else if (e->arg1 == 0 && e->arg2 < 0)
  54. {
  55. double i;
  56. if (modf (e->arg2, &i) == 0 && ((int64_t) i & 1) == 1)
  57. e->retval = copysign (__builtin_inf (), e->arg1);
  58. else
  59. e->retval = __builtin_inf ();
  60. }
  61. else
  62. return 0;
  63. }
  64. else if (__builtin_strcmp (n, "sqrt") == 0)
  65. {
  66. if (e->arg1 < 0)
  67. e->retval = __builtin_nan ("");
  68. else
  69. return 0;
  70. }
  71. else
  72. return 0;
  73. return 1;
  74. }
  75. #endif