From: Satoshi Nakagawa Date: 2007-08-20T23:32:48+09:00 Subject: [ruby-dev:31539] strtod の精度 中川といいます。 http://www.rubyist.net/~matz/20070803.html#p04 で言及されている、strtod の精度の件について提案があります。 http://d.hatena.ne.jp/hnw/20070802 のコメントで shiro さんが紹介していた、 「How to Read Floating Point Numbers Accurately (1990)」の2004年版 http://portal.acm.org/citation.cfm?id=989430&dl=&coll=&CFID=15151515&CFTOKEN=6184618 に、このアルゴリズムを David Gay が実装したという記述があります。 その実装の最新版は、おそらく、http://netlib.sandia.gov/fp/dtoa.c.gz だと 思うのですが、この実装を ruby 本体に取り込むことを提案します。 試しにこれを ruby 1.8 に組み込んでみました。 $ uname -mrs Darwin 8.10.1 i386 $ ./ruby -v ruby 1.8.6 (2007-08-20 patchlevel 5000) [i686-darwin8.10.1] 組み込み前: $ ./ruby -e 'printf("%21.0f\n", 36893488147419107329.0)' 36893488147419103232 組み込み後: $ ./ruby -e 'printf("%21.0f\n", 36893488147419107329.0)' 36893488147419111424 結果は、最近傍値への丸めになっていることがわかります。 PHP について、5.2.3 のソースコードを確認してみたところ、 zend_strtod.c は、David M. Gay の dtoa.c を改良(ARM 対応などを追加) したもののようです。 他にも、ECMA-262 2nd edition の 9.8.1 で Implementors of ECMAScript may find useful the paper and code written by David M. Gay for binary-to-decimal conversion of floating-point numbers: という記載があったり、 Mac OS X 10.4.10 の man 3 strtod の最後に AUTHORS The author of this software is David M. Gay. という記載があるので、それなりにメジャーな実装のようです。 ライセンス的にも、 * The author of this software is David M. Gay. * * Copyright (c) 1991, 2000, 2001 by Lucent Technologies. * * Permission to use, copy, modify, and distribute this software for any * purpose without fee is hereby granted, provided that this entire notice * is included in all copies of any software which is or includes a copy * or modification of this software and in all copies of the supporting * documentation for such software. と、missing/strtod.c のライセンスとあまり変わらないので、 LEGAL の記述を差し替える程度で済むと思うのですが、いかがでしょうか。 -- Satoshi Nakagawa http://d.hatena.ne.jp/Psychs/