37 lines
807 B
C++
Raw Normal View History

2023-07-02 19:51:09 +02:00
#include "mysqrt.h"
2022-11-16 20:14:03 +01:00
#include <cmath>
2019-11-11 23:01:05 +01:00
#include <iostream>
2023-07-02 19:51:09 +02:00
namespace mathfunctions {
namespace detail {
// a hack square root calculation using simple operations
double mysqrt(double x)
{
2016-07-09 11:21:54 +02:00
if (x <= 0) {
return 0;
2016-07-09 11:21:54 +02:00
}
2013-03-16 19:13:01 +02:00
2022-11-16 20:14:03 +01:00
// if we have both log and exp then use them
#if defined(HAVE_LOG) && defined(HAVE_EXP)
double result = std::exp(std::log(x) * 0.5);
std::cout << "Computing sqrt of " << x << " to be " << result
<< " using log and exp" << std::endl;
#else
2019-11-11 23:01:05 +01:00
double result = x;
// do ten iterations
2019-11-11 23:01:05 +01:00
for (int i = 0; i < 10; ++i) {
2016-07-09 11:21:54 +02:00
if (result <= 0) {
result = 0.1;
}
2019-11-11 23:01:05 +01:00
double delta = x - (result * result);
2016-07-09 11:21:54 +02:00
result = result + 0.5 * delta / result;
2019-11-11 23:01:05 +01:00
std::cout << "Computing sqrt of " << x << " to be " << result << std::endl;
2016-07-09 11:21:54 +02:00
}
2022-11-16 20:14:03 +01:00
#endif
return result;
}
2023-07-02 19:51:09 +02:00
}
}