Advertisement
Zgragselus

Reciprocals

Aug 16th, 2023
969
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.99 KB | None | 0 0
  1. #ifdef __cplusplus
  2.     #include <cstdint>
  3. #else
  4.     #include <stdint.h>
  5. #endif
  6.  
  7. __inline__ double __attribute__((const)) reciprocal( double x ) {
  8.     union {
  9.         double dbl;
  10.         #ifdef __cplusplus
  11.             std::uint_least64_t ull;
  12.         #else
  13.             uint_least64_t ull;
  14.         #endif
  15.     } u;
  16.     u.dbl = x;
  17.     u.ull = ( 0xbfcdd6a18f6a6f52ULL - u.ull ) >> 1;
  18.                                 // pow( x, -0.5 )
  19.     u.dbl *= u.dbl;             // pow( pow(x,-0.5), 2 ) = pow( x, -1 ) = 1.0 / x
  20.     return u.dbl;
  21. }
  22. __inline__ float __attribute__((const)) reciprocal( float x ) {
  23.     union {
  24.         float single;
  25.         #ifdef __cplusplus
  26.             std::uint_least32_t uint;
  27.         #else
  28.             uint_least32_t uint;
  29.         #endif
  30.     } u;
  31.     u.single = x;
  32.     u.uint = ( 0xbe6eb3beU - u.uint ) >> 1;
  33.                                 // pow( x, -0.5 )
  34.     u.single *= u.single;       // pow( pow(x,-0.5), 2 ) = pow( x, -1 ) = 1.0 / x
  35.     return u.single;
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement