Created
October 17, 2018 18:37
-
-
Save guitarrapc/28910fd74f8d596844bad17074f9755e to your computer and use it in GitHub Desktop.
C# version of Newton Raphson Method. Go : https://gist.github.com/guitarrapc/bdf51e61d50ad3e70b3bb2290797b5fe
This file contains 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
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