Using sqaure root in c++

Started by
6 comments, last by stickman 21 years, 11 months ago
can somone tell me how to do the sqaure root of something?? i wanna do this... sqaureroot of (25-x*x)... also what would i have to include at the top of my program.
Advertisement

  #include <cmath>// ...double n = sqrt(25-x*x);// ...  
Using just * / + - % how would you find a square root? do you just have to use "tril and error" to find it?
===========Jack!!!!!!
quote:Original post by Jack of Null Pointer
do you just have to use "tril and error" to find it?

No. I think there''s a series that you can use to find square roots. Even if there isn''t something as simple as a series, I know there are numerous algorithms for finding square roots. Do a little research with Google .

Do a search for Newton''s Method for finding square roots.
Don't have the time to test it but should work for value greater than 1 (you can easily adapt it for value between 0 and 1)

Newton iterative method :
float prev,next=real/2;do{   prev=next;   next=(prev+(real/prev))/2;}while((prev-next)>SQUARE_ROOT_PRECISION);return next; 
Feedback please!

[edited by - bloodscourge on May 4, 2002 5:03:41 PM]
I know that I don't know nothing... Operation Ivy
This is how you can use Newtons method to calculate it:

Newton''s method approximates the roots of an equation by constructing a tangent to the curve at a point (x = a, y = f(x)) and then finding the intersection of that point and the x axis (y = 0). This can be applied a few times and it will become more accurate as you continue. The formula used is this:

a = a - (f(a) / f''(a))

In this case, we want to find an a value, such that a^2 = n where n is the number we are finding the square root of:

a^2 = n

f(x) = a^2 - n

The derivative of this:

f''(x) = 2a

So, to approximate the square root of n, we use this (iterative) function:

a = a - ((a * a - n) / (2 * a))

You can loop this until floating point round off error means there is no more change.

You do need to choose an an initial value to start from, you could just use n for this. Note, that once n = a*a, then the value of a will not change:

a = a - ((n - n) / (2 * a))
a = a - 0
a = a

Trying is the first step towards failure.
Trying is the first step towards failure.
pssssssst the first post worked hehe

This topic is closed to new replies.

Advertisement