29 lines
526 B
C++
Raw Normal View History

2023-07-02 19:51:09 +02:00
#include "mysqrt.h"
2023-07-02 19:51:09 +02:00
#include <iostream>
2020-02-01 23:06:01 +01:00
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
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
}
return result;
}
2023-07-02 19:51:09 +02:00
}
}