I am trying to find the correct domain for the tan
function, I know that
tan x = sinx / cos x
and tan
is undefined when cos x = 0
. So
I am trying to check if cos x
is 0.
if ( Math.Cos(x).Equals(0) )
{
// do stuff
}
But this is never true because Math.Cos returns 6.123....E-17
How o check for cos == 0 ?
You need to broaden your expectations a bit - in order for Math.Cos(x)
to be genuinely equal to 0, you'd either need inaccuracy in Cos
(which will happen, of course) or for x
to have an irrational value.
Instead, you should work out some tolerance - some range of values for Math.Cos
which is very close to 0. For example:
if (Math.Abs(Math.Cos(x)) < 1e-15)
That 1e-15
is picked pretty much arbitrarily - you should work out what you want it to be for your particular task. (This will still give pretty enormous tan
values, of course...)
See more on this question at Stackoverflow