38 lines
787 B
C++
Raw Normal View History

2019-11-11 23:01:05 +01:00
#include <iostream>
2020-02-01 23:06:01 +01:00
#include "MathFunctions.h"
// include the generated table
#include "Table.h"
2020-02-01 23:06:01 +01: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
// use the table to help find an initial value
2019-11-11 23:01:05 +01:00
double result = x;
2016-07-09 11:21:54 +02:00
if (x >= 1 && x < 10) {
2020-08-30 11:54:41 +02:00
std::cout << "Use the table to help find an initial value " << std::endl;
result = sqrtTable[static_cast<int>(x)];
2016-07-09 11:21:54 +02:00
}
// 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;
}
2020-02-01 23:06:01 +01:00
}
}