JAVA: Math: Approximate The Square Root
Tarih: 5 Aralık 2013 Yorum: 0

(Math: approximate the square root) There are several techniques for implementing the sqrt method in the Math class. On such technique is known as the Babylonian method.  It approximates the square root of a number, n, by repeatedly performing a calculation using the following formula:

nextGues = (lastGuess + n / lastGuess) / 2

When nextGuess and lastGuess are almost identical, nextGuess is the approximated square root.  The initial guess can be any positive value (e.g., 1).  This value will be the starting value for lastGuess.  If the difference between nextGuess and lastGuess is less than a very small number, such as 0.0001, you can claim that nextGuess is the approximated square root of n.  If not, nextGuess becomes lastGuess and the approximation process continues.  Implement the following method that returns the square root of n.

public static double sqrt(long n)

 

SquareRoot.java

/**
 * Math: approximate the square root.
 */
 	import java.util.Scanner; // import Scanner.
public class SquareRoot {

    /** Main Method */
    public static void main(String[] args) {
    		long n = 0;

    	// Promt to user to enter decimal number.
    	Scanner input = new Scanner(System.in);
    		while(n <= 0){
    			prntStr("Enter the number: ");
    			n 	= input.nextLong();
    		}

    		double	result = sqrt(n); // Calculate square root.

    		prntStr("The square root of "+n+" is equal to "+result); // print.

    } // End of main method.

    /** sqrt method */
    public static double sqrt(long n){

    	double nextGuess,lastGuess;

    		for(lastGuess=1;Math.pow(lastGuess,2)<=n;lastGuess++){ // Find initial lastGuess.

    		}
				// square root calculate start.
    			nextGuess=(lastGuess+n/lastGuess)/2;

    			while(Math.abs(nextGuess-lastGuess)>= 0.0000001){

    				lastGuess=nextGuess;
    				nextGuess=(lastGuess+n/lastGuess)/2;

    			} // end of while.
    			// square root calculate end.

    	return nextGuess;

    } // End of sqrt method.

    /** prntStr Method */
    public static void prntStr (String s){

    	System.out.print(s);

    } // End of prnStr method.

} // End of public class.



Yorum Yok:


Yorum Yap:

Yorum yapabilmek için giriş yapmalısınız.




tema yapımcısı wordpress alexa bilgileri Webmaster Creative Commons v3 ile Lisanslanmıştır!


Akif ARSLAN © 2012 - 2019
Sitede bulunan istediğiniz cümleyi veya içeriği, istediğiniz gibi, istediğiniz yerde, istediğiniz zaman ve istediğiniz kişilerle paylaşabilirsiniz.