Last active
January 8, 2018 04:26
-
-
Save lbxa/24ae52e4090b3f9b54acf65e6b017dff to your computer and use it in GitHub Desktop.
Square root functions intended for use without <math.h> dependencies.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Square Root X | |
* | |
* Programatic attempt to solve square roots without <math.h> with | |
* brute force approach of either incrementing the square of 0.001 | |
* until square value is reached (toggling iterators for accuracy) | |
* or translate Newton's method into working C code. | |
* | |
* 02.05.17 | Lucas Barbosa | Open source software | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <assert.h> | |
#define CONVERGENCE_CHECK 2.25e-308 | |
#define NON_REAL 0 | |
#define DEFAULT_ITERATIONS 32 | |
double sqrtB(double square); | |
double sqrtX(double square); | |
void tests(void); | |
int main (void) { | |
tests(); | |
double mySquare = 0; | |
scanf("%lf", &mySquare); | |
double rootResult = sqrtX(mySquare); | |
printf("%lf\n", rootResult); | |
return EXIT_SUCCESS; | |
} | |
double sqrtB(double square) { | |
if (square <= NON_REAL) return 0; | |
double root = square / 3; | |
int i = 0; | |
/* | |
* @re-iterate arithmetic enough times for accurate successive | |
* approximations, it doesn't take many iterations. | |
*/ | |
while (i < DEFAULT_ITERATIONS) { | |
root = (root + square / root) / 2; | |
i++; | |
} | |
return root; | |
} | |
double sqrtX(double square) { | |
if (square <= NON_REAL) return 0; | |
double root = square / 3; | |
double last, diff = 1; | |
/* | |
* @perform the arithmetic over sufficient iterations, to provide | |
* successive approximations, convergence check is performed on the | |
* while loop restrictions between the difference of the re-iterated | |
* roots and their previous values (as last). | |
*/ | |
do { | |
last = root; | |
root = (root + square / root) / 2; | |
diff = root - last; | |
} while (diff > CONVERGENCE_CHECK || diff < -CONVERGENCE_CHECK); | |
return root; | |
} | |
void tests(void) { | |
assert((int)sqrtX(0) == 0); | |
assert((int)sqrtX(49) == 7); | |
assert((int)sqrtX(81) == 9); | |
assert((int)sqrtX(-2) == 0); | |
/// All tests were passed if code is compiled | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Optimisation includes using long doubles etc.