Java School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

 

Code Snippets

  

Java Source Code


Welcome to Dream.In.Code
Become a Java Expert!

Join 306,728 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 2,518 people online right now. Registration is fast and FREE... Join Now!





Finding Square Root Using Bisection Method

A method which will find the square root of a number, given the number to find the root of, as well as an adjustable precision

Submitted By: erik.price
Actions:
Rating:
Views: 218

Language: Java

Last Modified: November 6, 2009
Instructions: Using bisection might not be the most efficient way of finding square roots, but when given a perfect square, it will find the answer in only 1 iteration

Snippet


  1. public static double biSqrt(double root, double prec) {
  2.                 double low = 0;
  3.                 double high = Math.max(root, 1.0); //fixes a bug that would cause numbers less than 1 to fail
  4.                 double guess = (low+high)/2.0;
  5.                 int ctr = 0; //ctr is used to make sure that with some
  6.                         //numbers which can't be represented exactly don't inifitely repeat
  7.                 if(root < 0){
  8.                         return Double.longBitsToDouble(0x7ff8000000000000L);
  9.                         //this represents NaN (Not-a-Number) because negative
  10.                         //square roots don't work so well
  11.                 }
  12.                 else if(root == 0) {
  13.                         return 0; //prevents it from returning an incorrect result
  14.                         }
  15.                 while((Math.abs((guess*guess) - root) > prec) && (ctr < 1000)) //checks to see if the result is "good enough"
  16.                 {
  17.                         if((guess*guess) < root)
  18.                                 low = guess;
  19.                         else
  20.                                 high = guess;
  21.                         guess = (low+high) / 2.0;
  22.                         ctr++;
  23.                 }
  24.                 return guess;
  25.                
  26.                
  27.                 //just a note: you can remove the prec variable from the method and replace it with an unchanging hardcoded value for set precision
  28.         }

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live Java Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month