HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Approximating the square root using an iterative method

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
themethoditerativesquareusingrootapproximating

Problem

I wrote this code, based on the Newton-Raphson method, to find the square root of a number. I'm wondering how I can optimise this code, as I am out of ideas.

#include 

int main(void)
{
     float n, x, i;

     printf("Enter the number you wish to find the square root of.\n");
     printf("\n");
     scanf("%f", &n);

     x = n/2;

     for (i = 0; i < 100; i++)
         x = x - (((x*x) - n)/(2*x));

     printf("The square root of %.0f is %.4f.\n", n, x);

     return 0;

}

Solution

-
Do not rely on a fixed number of iterations. Stop when reaching a desired discrepancy (e.g. fabs(x*x - n)

-
I do not see any reason for not simplifying the calculations into
x = (x + n/x)/2.0`.

-
Assure that the input is positive.

Context

StackExchange Code Review Q#48725, answer score: 6

Revisions (0)

No revisions yet.