Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Created October 17, 2018 18:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guitarrapc/28910fd74f8d596844bad17074f9755e to your computer and use it in GitHub Desktop.
Save guitarrapc/28910fd74f8d596844bad17074f9755e to your computer and use it in GitHub Desktop.
void Main()
{
double input = 67000000000;
var result = Sqrt(input);
Console.WriteLine($"try: {result}");
Console.WriteLine($"math: {Math.Sqrt(input)}");
}
// input: 67000000000
// count: 24
// try: 258843.582110896
// math: 258843.582110896
double Sqrt(double x)
{
double prev,z = 1.0;
var i = 0;
var init = false;
const double threshold = 0.00000000001;
while (true)
{
i++;
prev = z;
z -= (z * z - x ) / (2 * z);
if (z == prev || (init && Math.Abs(prev) < Math.Abs(z + threshold)))
break;
init = true;
}
Console.WriteLine($"input: {x}");
Console.WriteLine($"count: {i}");
return z;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment