LoginSignup
6
5

More than 5 years have passed since last update.

Groovy なら単純な計算結果がおかしくない。COBOL も(コメント参照)。

Last updated at Posted at 2016-01-14

http://qiita.com/hkanda/items/e7c6001e356cfda3d783
を見て書いた。

以下、対話環境での断片と完全なプログラムがごっちゃになっているけど、1.1×2.2 をいろいろな言語でシンプルに書いてみた結果:

ruby2.3
1.1*2.2
#=> 2.4200000000000004
fortran
program TEST
  write(6,*) 1.1*2.2
  ! => 2.42000008    
end
python3.5
1.1*2.2
#=>2.4200000000000004
perl5.18
perl -e 'printf( "%.16f", 1.1*2.2 );'
#=>2.4200000000000004
node5.0.0
1.1*2.2
//=>2.4200000000000004
C
#include <stdio.h>

int main(){ printf( "%.16f\n", 1.1*2.2 ); return 0; }
/* =>2.4200000000000004 */
Java
class Hoge{
    public static void main( String[] args ){
        System.out.printf( "%.16f", 1.1*2.2 );
    }
}
//=>2.4200000000000004
PHP
<?
printf( "%.16f", 1.1*2.2 );
#=>2.4200000000000004

と、たいていの言語/処理系 では 1.1 のような表現は浮動小数点になるので誤差が出る。

そこで groovy。

groovy
printf( "%.20f", 1.1*2.2 );
// =>2.42000000000000000000

誤差なし。すばらしい。

※ COBOL でどうなるかを示してくださるコメント募集中 → 下記のコメントの通り、COBOL も内部は10進数のようです。

6
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5