0

I have this java code to calculate the sin(360):

if(re.equals(" sin "))
{
    try{
        String next=data.get(i+1);
        v1 = Double.parseDouble(next);
        double degreess = v1;
        double radianss = Math.toRadians(degreess);

        BigDecimal bDecimal1 = new BigDecimal(
            Math.sin(radianss), MathContext.DECIMAL32);

        re=""+bDecimal1;
        //re=""+Math.sin(Math.toRadians(Double.valueOf(next)));
        i++;
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

I expect sin(360) should be exactly 0.

But my result is non zero: -0.0000000000000002449294. Why is this not zero?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
kk yadav
  • 45
  • 1
  • 7
  • 2
    http://stackoverflow.com/questions/3961900/java-strange-behavior-with-sin-and-toradians http://stackoverflow.com/questions/6566512/getting-value-of-sine-180-as-1-22465e-16 – Josh Lee Mar 07 '13 at 13:26

2 Answers2

4

When dealing with floating point values, you should use abs(sin360 - 0) < delta (where delta is quite small like 0.0000001) instead of sin360 == 0. It's floating point internal representation issue. What Every Computer Scientist Should Know About Floating-Point Arithmetic

SpongeBobFan
  • 964
  • 5
  • 13
  • Why would you recommend evaluating this comparison? The code in the question does not contain any floating-point comparison, and the question makes no mention of wanting to compare floating-point values. There is nothing here to indicate the questioner wants to make such comparisons. They are asking why they got a value they did not expect. Evaluating the comparison you suggest does not change the value to one they expect or otherwise improve floating-point accuracy. It serves no purpose in this context. – Eric Postpischil Mar 07 '13 at 21:46
0

You could always use a decimal format:

DecimalFormat format = new DecimalFormat();
format.setMaximumFractionDigits(2);
System.out.println(format.format(bDecimal1));
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
vikingsteve
  • 38,481
  • 23
  • 112
  • 156