R:奇怪的触发函数行为 [英] R: Strange trig function behavior

查看:36
本文介绍了R:奇怪的触发函数行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为过渡到 R 的 Matlab 用户,我遇到了将三角函数应用于度数的问题.在 Matlab 中,弧度和度数都有三角函数(例如分别为 cos 和 cosd).R 似乎只包含弧度函数,因此需要我创建自己的(见下文)

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!

推荐答案

这是浮点运算:

> 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"?

这也是一个常见问题:http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f

这篇关于R:奇怪的触发函数行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆