R: Strange trig function behavior

2019-02-23 11:42发布

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!

5条回答
混吃等死
2楼-- · 2019-02-23 11:53

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楼-- · 2019-02-23 11:55

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.

查看更多
别忘想泡老子
4楼-- · 2019-02-23 11:56

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

查看更多
Explosion°爆炸
5楼-- · 2019-02-23 11:59

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

查看更多
劳资没心,怎么记你
6楼-- · 2019-02-23 12:09

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

查看更多
登录 后发表回答