R: Strange trig function behavior

梦想的初衷 提交于 2019-12-20 01:09:04

问题


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!


回答1:


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




回答2:


Looks like it's working fine to me. The value for pi probably isn't precise enough, so you are getting a very close estimate. If you think about it, 6.123234e-17 and -1.836970e-16 are very very close to 0, which is what the answer should be.

Your problem lies in the fact that while 90*pi/180 = pi/2 on paper, in computers, we use floating point numbers. I'm not sure what R/matlab use, but I'd definitely guess either a 32 bit or 64 bit floating point number. And you can only fit so much information in that limited number of bits, so you can't store every possible decimal.

You could modify your function so that given 90 or 270, return 0.




回答3:


This is a floating point representation error. See Chapter 1 of http://lib.stat.cmu.edu/s/Spoetry/Tutor/R_inferno.pdf




回答4:


The same reason that

1-(1/3)-(1/3)-(1/3)

doesn't equal 0. It has something to do with floating point numbers. I'm sure there will be more elaboration.




回答5:


You may also be interested in the zapsmall function for another way of showing numbers that are close to 0 as 0.



来源:https://stackoverflow.com/questions/5806807/r-strange-trig-function-behavior

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!