Kynian Kynian - 5 months ago 12
Java Question

tan() in java returning a strange value

I have a project Im working on where I need to pass an angle as 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. Here is my 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);
}
}
}

Answer

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?

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