9

My code passes an angle in radians to the cos, tan and sin. Everything seems to work fine except tan of 90, which gives the value 16331239353195370 for some odd reason. Example code:

import java.text.DecimalFormat;

public class mathtable {

  public static void main(String[] args) {

    System.out.println("Angle   Sin Cos Tan");
    System.out.println("-----   --- --- ---");

    for (double angle = 0.0; angle < 180; angle +=5) {
      double angle_rad = Math.toRadians(angle);
      double sin = Math.sin(angle_rad);
      String sin_4 = new DecimalFormat("#.####").format(sin);
      double cos = Math.cos(angle_rad);
      String cos_4 = new DecimalFormat("#.####").format(cos);
      double tan = Math.tan(angle_rad);
      String tan_4 = new DecimalFormat("#.####").format(tan);
      System.out.println(angle + "  " + sin_4 + "   " + cos_4 + "   " + tan_4);
    }
  }
}

Why is the value returned not strictly equal to IEEE infinity?

Kynian
  • 660
  • 4
  • 15
  • 30

1 Answers1

17

Well, tan(pi/2) in radians is essentially infinite, isn't it? So you'd expect to get a very large number, wouldn't you? (It's not infinity because pi/2 can't be exactly represented as a double. You're finding a value on an asymptotic curve very close to where it would become infinite.)

See these graphs of sin/cos/tan to see what I mean, remembering that pi/2 radians is 90 degrees.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Not pi/4 but pi/2 = 90 degrees. – Suzan Cioc Oct 03 '12 at 17:46
  • Actually tan(pi/2) is undefined and should return an error. The problem is, pi is not an exact value so tan(pi/2) is very big. – Caroline Jul 01 '14 at 11:46
  • @MartijnPieters: Added the graphs back now. Hopefully they'll stay around... (Another option is just to link to a Google search which shows the graph in the search results of course.) – Jon Skeet Jul 10 '16 at 19:23
  • I must have missed the meeting when it was decided that all very large values should be represented as the number 16331239353195370 :) – jwg Jul 11 '16 at 08:30
  • @jwg: Well don't forget that the input value isn't going to be *exactly* pi/2 radians... – Jon Skeet Jul 11 '16 at 08:31
  • @JonSkeet yup, it does; thank you for your prompt action, Jon! BTW note that pi/2 has to be *strictly smaller* than actual pi/2 (if it were larger, the result would be negative) –  Jul 11 '16 at 11:04
  • I had a similar problem when I implemented a quadratic equation solver, and the solution didn't *exactly* solve the original equation (but very close). Also in JUnit the exact double match is deprecated: https://stackoverflow.com/questions/5939788/junit-assertequalsdouble-expected-double-actual-double-epsilon – GregT Oct 02 '18 at 07:45