Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Strange trig function behavior

Tags:

r

trigonometry

As a Matlab user transitioning to R, I have ran across the problem of applying trigonometric functions to degrees. In Matlab there are trig functions for both radians and degrees (e.g. cos and cosd, respectively). R seems to only include functions for radians, thus requiring me to create my own (see below)

cosd<-function(degrees) {
  radians<-cos(degrees*pi/180)
  return(radians)
}

Unfortunately this function does not work properly all of the time. Some results are shown below.

> cosd(90)
[1] 6.123234e-17
> cosd(180)
[1] -1
> cosd(270)
[1] -1.836970e-16
> cosd(360)
[1] 1

I'd like to understand what is causing this and how to fix this. Thanks!

like image 936
KnowledgeBone Avatar asked Dec 04 '22 22:12

KnowledgeBone


1 Answers

This is floating point arithmetic:

> all.equal(cosd(90), 0)
[1] TRUE
> all.equal(cosd(270), 0)
[1] TRUE

If that is what you meant by "does not work properly"?

This is also a FAQ: http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f

like image 171
Gavin Simpson Avatar answered Dec 25 '22 07:12

Gavin Simpson