r - 添加 NA 和计算结果为 NaN 的表达式会根据顺序返回不同的结果,是否违反了交换性?

标签 r commutativity

我正在研究 R 中数字运算的极端情况。我遇到了以下涉及零除以零的特殊情况:

(0/0)+NA
#> [1] NaN
NA+(0/0)
#> [1] NA
创建于 2021-07-10 由 reprex package (v2.0.0)

session 信息

sessionInfo()
#> R version 4.1.0 (2021-05-18)
#> Platform: x86_64-apple-darwin17.0 (64-bit)
#> Running under: macOS Big Sur 10.16
#> 
#> Matrix products: default
#> BLAS:   /Library/Frameworks/R.framework/Versions/4.1/Resources/lib/libRblas.dylib
#> LAPACK: /Library/Frameworks/R.framework/Versions/4.1/Resources/lib/libRlapack.dylib
#> 
#> locale:
#> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
#> loaded via a namespace (and not attached):
#>  [1] digest_0.6.27     withr_2.4.2       magrittr_2.0.1    reprex_2.0.0     
#>  [5] evaluate_0.14     highr_0.9         stringi_1.6.2     rlang_0.4.11     
#>  [9] cli_3.0.0         rstudioapi_0.13   fs_1.5.0          rmarkdown_2.9    
#> [13] tools_4.1.0       stringr_1.4.0     glue_1.4.2        xfun_0.23        
#> [17] yaml_2.2.1        compiler_4.1.0    htmltools_0.5.1.1 knitr_1.33

这显然违反了加法的交换性质。我有两个问题:
  • 是否有基于 R 语言定义的这种行为的解释?
  • 是否有其他不涉及加数子表达式中副作用的违反加法交换属性的例子(包括在其他语言中)?
  • 最佳答案

    注意到

    0/0
    #[1] NaN
    
    + 行为的更一般示例问题如下:
    NA + NaN
    #[1] NA
     
    NaN + NA
    #[1] NaN
    
    这是在 r-devel thread和R核心团队成员Tomas Kalibera answers the following (我的重点和链接)。

    Yes, the performance overhead of fixing this at R level would be too large and it would complicate the code significantly. The result of binary operations involving NA and NaN is hardware dependent (the propagation of NaN payload) - on some hardware, it actually works the way we would like - NA is returned - but on some hardware you get NaN or sometimes NA and sometimes NaN. Also there are C compiler optimizations re-ordering code, as mentioned in ?NaN. Then there are also external numerical libraries that do not distinguish NA from NaN (NA is an R concept). So I am afraid this is unfixable. The disclaimer mentioned by Duncan is in ?NaN/?NA, which I think is ok - there are so many numerical functions through which one might run into these problems that it would be infeasible to document them all. Some functions in fact will preserve NA, and we would not let NA turn into NaN unnecessarily, but the disclaimer says it is something not to depend on.

    关于r - 添加 NA 和计算结果为 NaN 的表达式会根据顺序返回不同的结果,是否违反了交换性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68331524/

    相关文章:

    f# - 有没有更好的方法在 F#/OCaml 中编写交换函数?

    javascript - 了解仿函数法则 0​​x104567911

    haskell - 可交换模式匹配

    r - Dagger 出现在查看器的 ggplot 中,但在保存为 pdf 时替换为 ...

    类似于 Powershell 的运算符不可交换

    R:如何在不同的文件中设置断点?

    r - 数据表中不同变量的唯一观测数

    python - Sympy:用符号玻色子交换代替其数值

    r - 从 R 中的一组日期中提取工作日

    html - 在 R Shiny 标题中制作图像超链接