Home computickets Calculation of square root without library methods

# Calculation of square root without library methods

Author

Date

Category

How can I calculate a square root without using `sqrt (n) `and `n ^ 0.5 `?

The question actually has many solutions.

The most banal – half-division method.

``````double l = 0;
Double R = 1E100; //big number
Double M;
While (R - L & GT; 1E-8) {// Accuracy
M = L + (R - L) / 2;
if (m * m & gt; n) l = m;
ELSE R = M;
}
``````

There are more original ways, such as the calculation simulation in the column (here Example , code I will not bring)

Method is greater for C, but I think you can use in Java. Explanation

``````float q_rsqrt (float number)
{
Long I;
Float x2, y;
const float threehalfs = 1.5f;
x2 = Number * 0.5F;
Y = Number;
i = * (long *) & amp; y;
i = 0x5f3759df - (i & gt; & gt; 1);
y = * (Float *) & amp; i;
y = y * (threehalfs - (x2 * y * y)); // 1 iteration
// Y = Y * (Threehalfs - (x2 * y * y)); // 2 iteration, you can delete
RETURN 1 / Y;
}
``````

You can use logarithms

``````return math.exp (math.log (n) / 2);
``````

You can use numerical methods, for example Newton Method

``````double x = 1;
for (;) {
double nx = (x + n / x) / 2;
if (ABS (X - NX) & LT; 1E-10) Break; //accuracy
x = nx;
}
``````

There are many other ways, it all depends on specific requirements.

Write your own square root calculation function using Newton’s method (tangent) according to the formula

:

``````public static double sqrt (int number) {
Double T;
Double Squareroot = Number / 2;
do {
T = Squareroot;
SQUAREROOT = (T + (NUMBER / T)) / 2;
} While ((T - SQUAREROOT)! = 0);
Return Squareroot;
}
``````

IDEONE

It all depends on the context of the task. About various methods have already told. There is another option for the case if the range of input parameters is about known. You can simply make a table with ready-made answers.

When they did a coursework on microchemistry for 8 bit systems, then the easiest and rapid decision was the ROM to 256 cells with already covered there answers. But the teacher did not agree with this approach. Suggested still to “calculate.”

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.