Actual accuracy check. Added tests.
#include <math.h> double custom_sqrt (int a,int accuracy=20) { double fIntegerPart; double fFloatingPart = modf((double)sqrt(a), &fIntegerPart); double fTempFloat = fFloatingPart * pow(10, accuracy); double fTempInt; fTempFloat = modf(fTempFloat, &fTempInt); fTempFloat /= pow(10, accuracy); fFloatingPart -= fTempFloat; return fIntegerPart+fFloatingPart; }
double sqrt (int a,int accuracy=20) {double out = a;for(int i=0;i<accuracy;i++) {out = (out+a/out)/2;}return out;- #include <math.h>
- double custom_sqrt (int a,int accuracy=20) {
- double fIntegerPart;
- double fFloatingPart = modf((double)sqrt(a), &fIntegerPart);
- double fTempFloat = fFloatingPart * pow(10, accuracy);
- double fTempInt;
- fTempFloat = modf(fTempFloat, &fTempInt);
- fTempFloat /= pow(10, accuracy);
- fFloatingPart -= fTempFloat;
- return fIntegerPart+fFloatingPart;
- }
// TODO: Replace examples and use TDD development by writing your own tests Describe(square_root) { It(should_take_square_root) { Assert::That(custom_sqrt(4), Equals(2)); Assert::That(custom_sqrt(16), Equals(4)); Assert::That(custom_sqrt(169), Equals(13)); Assert::That(custom_sqrt(8, 2), Equals(2.82)); Assert::That(custom_sqrt(8, 5), Equals(2.82842)); } };
- // TODO: Replace examples and use TDD development by writing your own tests
- Describe(square_root)
- {
- It(should_take_square_root)
- {
Assert::That(sqrt(4), Equals(2));Assert::That(sqrt(16), Equals(4));Assert::That(sqrt(169), Equals(13));- Assert::That(custom_sqrt(4), Equals(2));
- Assert::That(custom_sqrt(16), Equals(4));
- Assert::That(custom_sqrt(169), Equals(13));
- Assert::That(custom_sqrt(8, 2), Equals(2.82));
- Assert::That(custom_sqrt(8, 5), Equals(2.82842));
- }
- };
Fundamentals
Removed iostream and cout. Because using printf instead of cout is a lot faster and optimized for the compiler.
Proof : https://godbolt.org/g/qqNUwM