Gerald
Gerald

Reputation: 541

How to use Newton-Raphson method to find the square root of a BigInteger in C#

So I'm attempting to use the Newton-Raphson method to find the square root of a BigInteger.

Here is my code:

            private void sqrRt(BigInteger candidate)
            {
                BigInteger epsilon = new BigInteger(0.0001);
                BigInteger guess = candidate / 2;

                while (BigInteger.Abs(guess * guess - candidate) >= epsilon)
                {
                    // guess = guess - (((guess**2) - y)/(2*guess))
                    guess = BigInteger.Subtract(guess, BigInteger.Divide(BigInteger.Subtract(BigInteger.Multiply(guess, guess), candidate), BigInteger.Multiply(2, guess)));
                    MessageBox.Show(Convert.ToString(guess));
                }
            }

The problem seems to be that the BigInteger is not precise enough to fall within the degree of accuracy of the epsilon in the while loop - i.e. it needs a decimal place. My question is what/how/where do I convert to a double to make the while loop eventually return false?

Upvotes: 0

Views: 904

Answers (1)

Joe Brunscheon
Joe Brunscheon

Reputation: 1989

You are using the wrong data type. In order to have decimal points, you would need to use double, float, decimal, or Complex.

Check the links of all these types so you can see their digits of precision.

Upvotes: 1

Related Questions