| 1 |
#include <cmath> |
| 2 |
#include <format> |
| 3 |
|
| 4 |
#include <MathLogger.h> |
| 5 |
|
| 6 |
#ifdef TUTORIAL_USE_SSE2 |
| 7 |
# include <emmintrin.h> |
| 8 |
#endif |
| 9 |
|
| 10 |
namespace { |
| 11 |
|
| 12 |
mathlogger::Logger Logger; |
| 13 |
|
| 14 |
#if defined(TUTORIAL_USE_GNU_BUILTIN) |
| 15 |
typedef double v2df __attribute__((vector_size(16))); |
| 16 |
|
| 17 |
double gnu_mysqrt(double x) |
| 18 |
{ |
| 19 |
v2df root = __builtin_ia32_sqrtsd(v2df{ x, 0.0 }); |
| 20 |
double result = root[0]; |
| 21 |
Logger.Log(std::format("Computed sqrt of {} to be {} with GNU-builtins\n", x, |
| 22 |
result)); |
| 23 |
return result; |
| 24 |
} |
| 25 |
#elif defined(TUTORIAL_USE_SSE2) |
| 26 |
double sse2_mysqrt(double x) |
| 27 |
{ |
| 28 |
__m128d root = _mm_sqrt_sd(_mm_setzero_pd(), _mm_set_sd(x)); |
| 29 |
double result = _mm_cvtsd_f64(root); |
| 30 |
Logger.Log( |
| 31 |
std::format("Computed sqrt of {} to be {} with SSE2\n", x, result)); |
| 32 |
return result; |
| 33 |
} |
| 34 |
#endif |
| 35 |
|
| 36 |
// a hack square root calculation using simple operations |
| 37 |
double fallback_mysqrt(double x) |
| 38 |
{ |
| 39 |
if (x <= 0) { |
| 40 |
return 0; |
| 41 |
} |
| 42 |
|
| 43 |
double result = x; |
| 44 |
|
| 45 |
// do ten iterations |
| 46 |
for (int i = 0; i < 10; ++i) { |
| 47 |
if (result <= 0) { |
| 48 |
result = 0.1; |
| 49 |
} |
| 50 |
double delta = x - (result * result); |
| 51 |
result = result + 0.5 * delta / result; |
| 52 |
|
| 53 |
Logger.Log(std::format("Computing sqrt of {} to be {}\n", x, result)); |
| 54 |
} |
| 55 |
return result; |
| 56 |
} |
| 57 |
|
| 58 |
#include <SqrtTable.h> |
| 59 |
|
| 60 |
double table_sqrt(double x) |
| 61 |
{ |
| 62 |
double result = sqrtTable[static_cast<int>(x)]; |
| 63 |
// do ten iterations |
| 64 |
for (int i = 0; i < 10; ++i) { |
| 65 |
if (result <= 0) { |
| 66 |
result = 0.1; |
| 67 |
} |
| 68 |
double delta = x - (result * result); |
| 69 |
result = result + 0.5 * delta / result; |
| 70 |
} |
| 71 |
Logger.Log( |
| 72 |
std::format("Computed sqrt of {} to be {} with TableSqrt\n", x, result)); |
| 73 |
return result; |
| 74 |
} |
| 75 |
|
| 76 |
double mysqrt(double x) |
| 77 |
{ |
| 78 |
if (x >= 1 && x < 10) { |
| 79 |
return table_sqrt(x); |
| 80 |
} |
| 81 |
|
| 82 |
#if defined(TUTORIAL_USE_GNU_BUILTIN) |
| 83 |
return gnu_mysqrt(x); |
| 84 |
#elif defined(TUTORIAL_USE_SSE2) |
| 85 |
return sse2_mysqrt(x); |
| 86 |
#else |
| 87 |
return fallback_mysqrt(x); |
| 88 |
#endif |
| 89 |
} |
| 90 |
} |
| 91 |
|
| 92 |
namespace mathfunctions { |
| 93 |
double sqrt(double x) |
| 94 |
{ |
| 95 |
#ifdef TUTORIAL_USE_STD_SQRT |
| 96 |
return std::sqrt(x); |
| 97 |
#else |
| 98 |
return mysqrt(x); |
| 99 |
#endif |
| 100 |
} |
| 101 |
} |