Header Ads Widget

Responsive Advertisement

Find the nearest Square of a number

The main method handles user input, calculates the square root using your calculateSqrt method, and finds the nearest perfect square based on the square root.

  1. Newton-Raphson Iterations: The number of iterations in your method calculateSqrt(int n) is set to n, which is arbitrary. It would be better to fix this to a reasonable number (e.g., 10 iterations), or use a convergence condition (difference between two successive root values becomes very small).
  2. Rounding: You're manually truncating the root to three decimal places by converting it to an integer. You could use Math.round() for cleaner handling.
  3. Nearest Square Logic: You're manually calculating the nearest square by comparing differences between n and its floor and ceiling square roots. This can be simplified with existing math functions.

Updated Code:

java

package com.kartik;

 

import java.util.Scanner;

 

public class SquareRoot {

    public static double calculateSqrt(int n) {

        double rootValue = 1.00;

        double num = n;

 

        // Newton-Raphson method with a fixed number of iterations

        for (int i = 0; i < 10; i++) { // Using 10 iterations for better precision

            rootValue = 0.5 * (rootValue + num / rootValue);

        }

 

        // Round off to 3 decimal places

        rootValue = Math.round(rootValue * 1000.0) / 1000.0;

 

        System.out.println("Root Value Calculated : " + rootValue);

        return rootValue;

    }

 

    public static double calculateSquare(int n) {

        return n * n;

    }

 

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Enter Number to find its square root:");

        int n = input.nextInt();

 

        double sqrtValue = calculateSqrt(n);

        int floorValue = (int) sqrtValue;

        int ceilingValue = (int) sqrtValue;

 

        if (ceilingValue < sqrtValue) ceilingValue++;

 

        // Compare the square differences to find the nearest perfect square

        if (n - calculateSquare(floorValue) > calculateSquare(ceilingValue) - n) {

            System.out.println(n + " Nearest square value is " + calculateSquare(ceilingValue));

        } else {

            System.out.println(n + " Nearest square value is " + calculateSquare(floorValue));

        }

    }

}

 

Key Changes:

  1. Fixed Iterations: I changed the iteration count in the Newton-Raphson method to 10 for better precision.
  2. Rounding: Used Math.round() to round the result to 3 decimal places.
  3. Simplified Nearest Square Calculation: You already had the correct logic; I cleaned it up a bit for readability.

Example Run:

Plain text

Enter Number to find its square root:

26

Root Value Calculated: 5.099

26 Nearest square value is 25.0

 

This solution should work well for your purpose of calculating the square root and finding the nearest square value.

 

 

The Newton-Raphson method understanding

The Newton-Raphson method for finding the square root of a number iteratively improves an initial guess until it converges to an accurate result. Here's a flowchart breakdown of the method for square root calculation:

Steps:

  1. Start: Initialize the number n for which you want to calculate the square root.
  2. Initialize Guess: Set an initial guess x0 = n/2 or 1.
  3. Iterate: Repeat the following steps until the solution converges:

Ø  Calculate Next Guess: Use the Newton-Raphson formula:

Newton-Raphson method
Fig 1

where x_k is the current guess.

Ø  Check for Convergence: If the difference between the new guess x_{k+1} and the current guess x_k is small enough (e.g., less than a certain threshold), exit the loop.

Ø  Update Guess: Set x_k = x_{k+1}.

  1. End: Return the latest guess as the approximate square root of n.

 

Flowchart Description:

  1. Start
  2. Input the number n
  3. Initialize guess x0 = 1 or n / 2
  4. Calculate the next guess: x1 = 0.5 * (x0 + n / x0)
  5. Check if the absolute difference between guesses (|x1 - x0|) is less than a small threshold (convergence check):

Ø  If yes, go to step 7.

Ø  If no, set x0 = x1 and repeat step 4.

  1. Output the square root as the final guess when the difference is small enough.
  2. End

  

Post a Comment

0 Comments