

タイトルの通りなのですが，Rで0.17 * 10000 ==
1700の真偽を判定させると，FALSEが返ってきます。以下はTRUEと判定されます（当然ですが…）。  
1700 * 1 == 1700  
170 * 10 == 1700  
17 * 100 == 1700  
1.7 * 1000 == 1700  
Rが正しく計算できていないように見えるにははなぜでしょうか？また解消法はあるでしょうか？  
追記：0.28 * 10000 == 2800も同様でした。


CC BY-SA 4.0
2023-06-02T06:36:14.187
95071
2023-06-02T06:52:33.010
2023-06-02T06:37:23.057
58563
58563
question
r
Rで0.17 * 10000 == 1700がFALSEになる理由と解消法


help メッセージで言及されています。

[code]

    $ R
    
    R version 4.2.2 Patched (2022-11-10 r83330) -- "Innocent and Trusting"
    Copyright (C) 2022 The R Foundation for Statistical Computing
    
    > ?"=="
    
                              :
    Note:
    
         Do not use ‘==’ and ‘!=’ for tests, such as in ‘if’
         expressions, where you must get a single ‘TRUE’ or ‘FALSE’.
         Unless you are absolutely sure that nothing unusual can happen,
         you should use the ‘identical’ function instead.
    
         For numerical and complex values, remember ‘==’ and ‘!=’ do
         not allow for the finite representation of fractions, nor for
         rounding error.  Using ‘all.equal’ with ‘identical’ or
         ‘isTRUE’ is almost always preferable; see the examples.  (This
         also applies to the other comparison operators.)
    
                              :
    Examples:
    
         x1 <- 0.5 - 0.3
         x2 <- 0.3 - 0.1
         x1 == x2                   # FALSE on most machines
         isTRUE(all.equal(x1, x2))  # TRUE everywhere
    
[/code]

なので、以下の様にします。

[code]

    > isTRUE(all.equal(0.17 * 10000, 1700))
    [1] TRUE
    
[/code]


CC BY-SA 4.0
2023-06-02T06:52:33.010
95072
2023-06-02T06:52:33.010
47127
95071
answer