How to check if Math.cos (angle) = 0 matches

I am trying to find the correct domain for the function tan, I know that

tan x = sinx / cos x

and tan- undefined when cos x = 0. So

I am trying to check if cos x0 is.

 if ( Math.Cos(x).Equals(0) )
 {
     // do stuff
 }

But this is never the case, because Math.Cos returns. 6.123....E-17 How o check for cos == 0?

+4
source share
3 answers

You need to slightly increase your expectations - in order to Math.Cos(x)be truly equal to 0, you would need an inaccuracy in Cos(which, of course, will happen) or for x, in order to have an irrational value.

- Math.Cos, 0. :

if (Math.Abs(Math.Cos(x)) < 1e-15)

, 1e-15 - , , . ( tan, ...)

+11

Math.Tan, Math.Tan . , , Double.NaN () Double.PositiveInfinity/Double.NegativeInfinity, :

double t = Math.Tan(something);

if (!double.IsInfinity(t) && !double.IsNaN(t))
{
    // Do Something
}
+4

, , - , .

, :

const double Epsilon = 0.0001;

if (Math.Cos(x) < Epsilon)
{
    // Code here
}

, Math.Cos(x).Equals(-), .

If you need more information about why your code does not work, you can see it here: http://www.parashift.com/c++-faq/floating-point-arith.html

This is a FAQ for C ++, but the same goes for your case.

+2
source

All Articles