We help IT Professionals succeed at work.

Precision

kenchan2000
kenchan2000 asked
on
Medium Priority
350 Views
Last Modified: 2010-03-31
public class Square
{
   public static void main (String args[])
   {
        System.out.println("Square is : " + 1.13*1.13);
   }
}

How is the normal implementation to tackle with such problem of precion?
Comment
Watch Question

Commented:
> java Square

Square is : 1.2769

what's the problem ?
Hi kenchan2000,

 Usual way for tackel precision is Use java.math package.
i.e. use BigInteger or BigDecimal class. It allow U to round the values to your requried position.
Generic Example:

/*********************** code ***************************

import java.math.*;
public class Square
{
  public static void main (String args[])
  {
       double val = 1.13;
       int denominator = 1;
       int precision=3;
       System.out.println("Square is : " + val * val);
       try {
            BigDecimal bigDinom = new BigDecimal(denominator);
            BigDecimal doubleVal = new BigDecimal(val);
            doubleVal = doubleVal.divide(bigDinom,precision,doubleVal.ROUND_HALF_DOWN);
            System.out.println("Square is: Of BigDecimal " + doubleVal);
            val = doubleVal.doubleValue();
            System.out.println("Square is: Double " + val);
       } catch(ArithmeticException ae){
            System.out.println("Err" + ae.getMessage());
       }
  }
}

/********************* End code **************************

Hope this will help you.

Commented:
About floating point precision read here:

http://www.math.grin.edu/~stone/courses/fundamentals/IEEE-reals.html

There may be other resources on the net suitable for you, but you need to specify your question further.

Cheers,
  Nik

Explore More ContentExplore courses, solutions, and other research materials related to this topic.