Is there a fast standard C or C ++ library for double precision inverse square root?

I find myself typing

double foo=1.0/sqrt(...); 

a lot, and I heard that modern processors have built-in inverse square root operation codes.

Is there a library of standard or root functions of a standard C or C ++ library that

  • uses a smooth spot with double precision?
  • is as accurate as 1.0/sqrt(...) ?
  • as fast or faster than the result of 1.0/sqrt(...) ?
+6
source share
5 answers

No. No no. Not in C ++. No.

+9
source

You can use this function to calculate the inverse square root faster.
Wikipedia has an article on how this works: https://en.wikipedia.org/wiki/Fast_inverse_square_root
There is also a C version of this algorithm.

 float invSqrt( float number ){ union { float f; uint32_t i; } conv; float x2; const float threehalfs = 1.5F; x2 = number * 0.5F; conv.f = number; conv.i = 0x5f3759df - ( conv.i >> 1 ); conv.f = conv.f * ( threehalfs - ( x2 * conv.f * conv.f ) ); return conv.f; } 
0
source

why not try it? #define INSQRT(x) (1.0/sqrt(x))

It is just as fast, requires less input (makes you feel like its function), uses double precision, exact as 1 / sqrt (..)

-1
source

If you repeat the same thing over and over again, you should think of yourself as a β€œfunction!”:

 double invsqrt(const double x) { return 1.0 / std::sqrt(x); } 

Now the code is more self-documenting: people do not need to output 1.0 / std::sqrt(x) - this is the inverse square root, they read it. In addition, you can now connect to any specific implementation, and each call site automatically uses the updated definition.

To answer your question, no, there is no C (++) function for it, but now that you have created it, if you find that your performance is too insufficient, you can replace your own definition.

-1
source

If you are not afraid to use your own functions, try the following:

 template <typename T> T invsqrt(T x) { return 1.0 / std::sqrt(x); } 

It should be as fast as the original 1.0 / std::sqrt(x) in any modern optimized compiler. In addition, it can be used with doubles or floats.

-1
source

Source: https://habr.com/ru/post/1440149/


All Articles