ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Using Java Big Decimal to compute square roots of large numbers

Updated on November 4, 2012

The standard number classes in Java are adequate for most purposes, but occasionally a calculation cannot safely be carried out with the standard classes: I once worked for a bank that insisted calculations be carried out using infinite precision arithmetic. Java caters for infinite precision arithmetic- the BigInteger and BigDecimal classes give infinite precision arithmetic in return for a large performance overhead, inelegant code and the need to worry about whether an operation, such as finding the square root of a number, will terminate or run for ever. Here two iterative algorithms are compared with each other and with the the Java Math.sqrt() method.

The code samples supplied here come with no guarantee whatsoever. Use at your own risk

The Test Problem

One of the problems on Project Euler involved finding the square root of


This is 74 decimal digits long and the root is approximately


The implementation of each of the algorithms described here was tested on small numbers the exact value of which could be calculated by hand. As expected the algorithms did not give exact results, for example the square root of 196 was found to be 13.999999........ with some other digits after the ellipse. Apart from this the results were correct.

Big Integer and Big Decimal

These classes provide infinite precision arithmetic and useful methods, such as isProbablePrime() and gcd() not offered by the standard types: long, integer, double etc. Using them for simple operations is cumbersome, and comparing two BigNumbers means a lot of typing. Sometimes just constructing one seems awkward. One reason for this is that the standard operators have not been overloaded.

A key class, MathContext, restricts the number of decimal places to which a calculation is carried out and is essential when a calculation ( √2 for example) will never end. For this investigation the precision was set at one hundred decimal placed.

Code for Babylonian Method

	public  static BigDecimal bigsqrtBabylonian(BigDecimal anumber,String aPrecision)
		int exponent = anumber.toString().length()/2;
		BigDecimal guess = BigDecimal.TEN.pow(exponent);
		BigDecimal precision = new BigDecimal(aPrecision);
		BigDecimal nextguess = TWO;

		    BigDecimal theError = guess.subtract(nextguess);
		    while(theError.abs().compareTo(precision) >0)
// nextguess = 0.5*(guess + anumber/guess)
// mc is a class variable. 
		       nextguess = anumber.divide(guess,mc);
		       nextguess = nextguess.add(guess);
		       nextguess = nextguess.multiply(HALF);
		       theError = guess.subtract(nextguess);
		       guess = nextguess;
	    return guess; 

The "Babylonian" Algorithm

Wikipedia discusses several algorithms for calculating square roots most of which are interesting but of limited use or of historical interest only. A reasonably fast algorithm that would give accurate results was needed. Wikipedia and various other places produced two possibilities, both iterative methods (Iterative methods have the advantage of being intuitive and easy to understand ): The Babylonian or Heron method, which is known to converge rapidly and a binary search method that should be logarithmic in the size of the input. Other algorithms such as Chebyshev polynomials methods were left for future investigations. Further aspects like the scale were not used in this first pass.

The Babylonian method, a case of Newton's method starts with a guess at the square root then refines it iteratively. It is a case of Newton's method.

Let anumber is the number whose root is desired, guess the current estimate of the square root and precision the desired precision. The algorithm is:

guess = initial estimate

nextguess = 1000-0*

while( | nextguess -guess | > desired_precision)


nextguess = 0.5*(guess + anumber/guess)


return nextguess

This converges rapidly. Normally only a few iterations are needed to reach a high precision ( around a dozen for a simple case, according to Wikipedia).

A binary Chop Algorithm

The alternative was a binary search

  1. delta = anumber/2

  2. guess = delta/2

  3. desiredprecision = 1.0E-100 ( change to taste)

  4. guesssquared = guess*guess

  5. if(guesssquared > anumber) guess = guess -delta

  6. if(guesssquared < anumber) guess = guess +delta

  7. if( abs(guesssquared - guess*guess) < desiredprecision ) return guess

  8. delta = delta/2

This needs a multiplication where the Babylonian method has a division and a multiplication. It is also theoretically more elegant. So the guess was these two forces would balance out. This turned out to be wrong.


Big Decimal Babylonian method precision 10**-100 0.51 milliseconds (averaged over 1000 iterations)

Big Decimal iterative method precision 10**-100 37 milliseconds (averaged over 1000 iterations)

By comparison the standard Java square root algorithm for a double took around 100 nanoseconds and a version of the Babylonian Algorithm for a double that did not use infinite precision arithmetic took around 2 microseconds.


Despite any weaknesses in the method of measurement it seems clear that BigDecimal calculations have an enormous overhead, compared with the limited precision of the square root calculation of the Java Math package. The only surprise is the magnitude of the overhead

It is also apparent that for high precision calculations the “Babylonian” method converges much faster, for the same precision, than the iterative methods though this advantage is reduced as the precision decreases. The same effect is seen for the fixed precision calculations of the Java Math package.

BigDecimal and Big Integer calculations should only be used when unavoidable or when speed is not critical but precision is critical.

The original goal of deciding whether the “Babylonian” or “iterative” algorithm is faster was achieved. The “Babylonian” algorithm won decisively. It seems unlikely changing implementation details will alter this.


    0 of 8192 characters used
    Post Comment

    No comments yet.


    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at:

    Show Details
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)