Archived

This topic is now archived and is closed to further replies.

stickman

Using sqaure root in c++

Recommended Posts

stickman    122
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.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster

  
#include <cmath>

// ...


double n = sqrt(25-x*x);

// ...

Share this post


Link to post
Share on other sites
Null and Void    1088
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 .

Share this post


Link to post
Share on other sites
BloodScourge    122
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]

Share this post


Link to post
Share on other sites
ragonastick    134
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.

Share this post


Link to post
Share on other sites