0

If have this code:

double sin = Math.sin(angle*rad);
double cos = Math.cos(angle*rad);
double tan = Math.tan(angle*rad);

It returns the triangle function for a specified angle. However for degrees of angle, like 90, -0.00000 is returned. So when these values are printed out, -0 just looks weird. How would -0 be tested for in an if statement?

I have tried with this code:

if (tan==0) { s.o.p(tan); }

and it doesn't run.

Khalid Shah
  • 3,132
  • 3
  • 20
  • 39
crazicrafter1
  • 309
  • 5
  • 18

2 Answers2

1

Just take the absolute value on the variable when you compare it with zero. You will likely need to cover a range since it's not always likely to be exactly 0.0.

if (Math.abs(tan) <= threshold) { ... }

Where you set threshold to a small enough value to cover what you consider is close enough to 0.

Edit: Added threshold/epsilon value in comparison - thanks Ben

Johan
  • 3,577
  • 1
  • 14
  • 28
  • Which will probably not work because it's not exactly 0 but in a small range around 0. So you probably rather want to define an epsilon so that `Math.abs(tan) < epsilon` – Ben Oct 16 '18 at 11:56
  • @Ben Good call, I've added it to my answer. Thank you. – Johan Oct 16 '18 at 12:45
0

You can check for negative zero by dividing 1 by your value. This will yield Double.POSITIVE_INFINITY for a positive zero and Double.NEGATIVE_INFINITY for a negative zero:

if (1.0 / value == Double.NEGATIVE_INFINITY) {
    // Value was a negative zero
}
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79