R:奇怪的三角函数行为
作为一名过渡到 R 的 Matlab 用户,我遇到了将三角函数应用于度数的问题。在Matlab 中,有弧度和度数的三角函数(例如分别为cos 和cosd)。 R 似乎只包含弧度函数,因此需要我创建自己的函数(见下文)
cosd<-function(degrees) {
radians<-cos(degrees*pi/180)
return(radians)
}
不幸的是这个函数并不总是正常工作。一些结果如下所示。
> cosd(90)
[1] 6.123234e-17
> cosd(180)
[1] -1
> cosd(270)
[1] -1.836970e-16
> cosd(360)
[1] 1
我想了解造成此问题的原因以及如何解决此问题。谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是浮点算术:
如果这就是您所说的“无法正常工作”的意思?
这也是一个常见问题解答: http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f
This is floating point arithmetic:
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
看起来对我来说效果很好。 pi 的值可能不够精确,因此您得到的估计值非常接近。如果你仔细想想,6.123234e-17 和 -1.836970e-16 非常非常接近 0,这就是答案应该是的。
你的问题在于,虽然纸上的 90*pi/180 = pi/2,但在计算机中,我们使用浮点数。我不确定 R/matlab 使用什么,但我肯定会猜测是 32 位还是 64 位浮点数。而且您只能在有限的位数中容纳这么多信息,因此您无法存储所有可能的小数。
您可以修改您的函数,以便给定 90 或 270,返回 0。
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.
这是浮点表示错误。请参阅 http://lib.stat.cmu.edu/s 的第 1 章/Spoetry/Tutor/R_inferno.pdf
This is a floating point representation error. See Chapter 1 of http://lib.stat.cmu.edu/s/Spoetry/Tutor/R_inferno.pdf
同样的原因
不等于0。它与浮点数有关。我相信会有更多的阐述。
The same reason that
doesn't equal 0. It has something to do with floating point numbers. I'm sure there will be more elaboration.
您可能还对 zapsmall 函数感兴趣,它以另一种方式将接近 0 的数字显示为 0。
You may also be interested in the zapsmall function for another way of showing numbers that are close to 0 as 0.