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,494 people online right now. Registration is fast and FREE... Join Now!





Finding Square Root Using the Newton Rhapson Method

Demonstrates the method for finding square root using the Newton Rhapson method, which is commonly used in calculators

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

Language: Java

Last Modified: November 6, 2009
Instructions: Similar to the bisection method in design, but this method will perform better in almost every case (excluding perfect numbers, it'll find the answer, but just in a few more iterations)

Snippet


  1. public static double newtonSqrt(double x, double epsilon)
  2.                 {
  3.                         int ctr = 0; //ctr makes sure that the function will terminate eventually
  4.                         double guess = 10; //initial guess to check
  5.                         double result = guess-((guess*guess-x)/(2*guess));
  6.                         if(x < 0){
  7.                                 return Double.longBitsToDouble(0x7ff8000000000000L);
  8.                                 //this represents NaN (Not-a-Number) because negative
  9.                                 //square roots don't work so well
  10.                         }
  11.                        
  12.                         else if(x == 0){
  13.                                 return 0; //prevents it from returning an incorrect answer
  14.                         }
  15.                         while((Math.abs(result*result - x) > epsilon) && ctr < 1000)
  16.                         {
  17.                                 guess = result;
  18.                                 result = guess - ((guess*guess-x)/(2*guess));
  19.                                 ctr++;
  20.                         }
  21.                         return result;
  22.                         //note: you can remove the epsilon variable from the method and replace it with an unchanging hardcoded value for set precision
  23.                 }

Copy & Paste


Comments


pbl 2009-11-10 23:28:41

Good show... now we can redirect all those f* questions here


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