Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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 ?

like image 945
giannisf Avatar asked Dec 02 '22 17:12

giannisf


1 Answers

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...)

like image 145
Jon Skeet Avatar answered Dec 14 '22 11:12

Jon Skeet