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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With