Tuesday, July 14, 2009

How do you get the square root of a number in c++ without the sqrt function? (In math terms)?

Thanks.

How do you get the square root of a number in c++ without the sqrt function? (In math terms)?
Start with a guess, say x which will incorrect by dx. Square your guess:





(x + dx) = x^2 + 2dx + dx^2





ignoring the dx^2 because it will become very small, 2dx is approximately the error. Deduct the square of you guess from the result and divide by 2, add this result to your guess and keep going until you hit the correct value.























_
Reply:Use the brute force method try each number in sequence from 1
Reply:you can use a method which is called newtons method or something like that. You say 'n' is the number you want to find the root of and 'x' is a starting guess. The lines are:





int n = 4; /* or any other number */


int x = 1; /* or any number except 0 */


x = ((x+ (n / x) / 2);





I might have used too many parentheses. Anyways, here is how it works, if you don't already understand. 'x' can be any number except 0, but the closer 'g' is to the square root of 'x', the less times you will have to do the formula. You are basically starting with any number, it being a factor of 'n'.


(n / x) finds the other factor. This plus 'x' and then divided by 2 finds the mean of the two factors and stores this as the new 'x'. Every iteration of this formula causes 'x' to get closer and closer to the square root of 'n'. It is suprisingly fast, taking only 5 or 6 cycles for maximum precision if your guess is fairly close. I'm sure you could just put it in a for() loop for a large number of iterations to obtain a very close estimate.
Reply:It very simple to calculate square root of a number with out using sqrt function.


first assume a number as sqrt and apply newton repson method. u will get sqrt of any number.


No comments:

Post a Comment