Thursday, October 29, 2009

Square root without Math.sqrt:

Here is the java program to find sqrt of a number without the Math.sqrt function.
You can also convert into c program in simple way.

class square
{
public static void main(String args[])
{
double x=5;
double y;
double j,i;
for(i=1.000000;(i*i)<5;i=i+0.000001)
{
}
j=i;
i=i-0.000001;
y=(j+i)/2;
System.out.println("y="+y);
}
}

Output:
y=2.2360674999507304

The square root of the number.

In this program I initialized that x=5.
The for loop continue until square of the i is smaller than 5.
When it’s larger it’ll come out of the loop.
When i=2.2360679999507305 it’ll come out of the loop
Then j=i now j=2.2360679999507305
i=i-0.000001
now i will become i=2.2360669999507303
y=(j+i)/2 y value is average of j,i(because the square root’ll between the smaller and larger value)
so now y will becomesquare root of the number.

Using this method try to write c program yourself (it’s simple because I give algorithm).
If you can’t able to write ,post a comment.

0 comments:

Post a Comment