#include <stdio.h>

double squareRoot(double N) {
    if (N < 0) {
        printf("Negative numbers do not have real square roots.\n");
        return -1; // Indicate an error for negative input
    }

    double guess = N; // Start with the number itself as the initial guess
    double epsilon = 0.00001; // Define the accuracy level
    double newGuess;

    // Repeat until the guess is close enough to the actual square root
    do {
        newGuess = (guess + N / guess) / 2; // Update guess using the formula
        // Check if the difference is within the acceptable range
        if (newGuess - guess < epsilon && newGuess - guess > -epsilon) {
            break; // If close enough, break the loop
        }
        guess = newGuess; // Update the guess
    } while (1);

    return newGuess; // Return the approximated square root
}

int main() {
    double number;

    printf("Enter a number to find its square root: ");
    scanf("%lf", &number); // Take user input

    double result = squareRoot(number); // Call the function
    if (result != -1) { // Check for negative input
        printf("The square root of %.2lf is approximately %.5lf\n", number, result);
    }

    return 0;
}

Explanation:

The program uses the Newton-Raphson method, an iterative technique to estimate the square root of a number.

Key Components

  1. Function squareRoot(double x):
    • Starts with an initial guess (g = x / 2).
    • Iteratively improves the guess using the formula: g=g+xg2g = \frac{g + \frac{x}{g}}{2}g=2g+gx​​
    • Continues until the guess is sufficiently close to the actual square root (within a small threshold, epsilon).
  2. Main Function:
    • Prompts the user for a number.
    • Checks if the number is negative (since square roots of negatives are not real).
    • Calls the squareRoot function and displays the result

Output:

1.Enter a number to find its square root: -9 
Cannot compute square root of a negative number.

2. Enter a number to find its square root: 36
The square root of 36.00 is approximately 6.00000

3. Enter a number to find its square root: 50 
The square root of 50.00 is approximately 7.07107

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights