gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 04:26:36 25 4
gpt4 key购买 nike

我正在研究 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 toolarge and it would complicate the code significantly. The result ofbinary operations involving NA and NaN is hardware dependent (thepropagation of NaN payload) - on some hardware, it actually works theway we would like - NA is returned - but on some hardware you get NaN orsometimes NA and sometimes NaN. Also there are C compiler optimizationsre-ordering code, as mentioned in ?NaN. Then there are also externalnumerical libraries that do not distinguish NA from NaN (NA is an Rconcept). So I am afraid this is unfixable. The disclaimer mentioned byDuncan is in ?NaN/?NA, which I think is ok - there are so many numericalfunctions through which one might run into these problems that it wouldbe infeasible to document them all. Some functions in fact will preserveNA, and we would not let NA turn into NaN unnecessarily, but thedisclaimer says it is something not to depend on.

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

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com