Project

General

Profile

Actions

Bug #6741

closed

(1 << 103).to_f.to_s is "10141204801825835000000000000000.0"

Added by akr (Akira Tanaka) over 12 years ago. Updated over 12 years ago.

Status:
Closed
Assignee:
-
Target version:
ruby -v:
ruby 2.0.0dev (2012-07-15 trunk 36395) [x86_64-linux]
Backport:
[ruby-dev:45960]

Description

気がついたのですが、Float#to_s が実際には 0 でない桁を 0 とした文字列を生成することがあります。

% ./ruby -ve '1.upto(200) {|i| p [i, (1 << i).to_f.to_s] }'
ruby 2.0.0dev (2012-07-15 trunk 36395) [x86_64-linux]
[1, "2.0"]
[2, "4.0"]
[3, "8.0"]
[4, "16.0"]
[5, "32.0"]
[6, "64.0"]
[7, "128.0"]
[8, "256.0"]
...
[54, "18014398509481984.0"]
[55, "36028797018963970.0"]
[56, "72057594037927940.0"]
[57, "144115188075855870.0"]
[58, "288230376151711740.0"]
[59, "576460752303423500.0"]
[60, "1152921504606847000.0"]
[61, "2305843009213694000.0"]
[62, "4611686018427388000.0"]
[63, "9223372036854776000.0"]
[64, "18446744073709552000.0"]
[65, "36893488147419103000.0"]
[66, "73786976294838210000.0"]
[67, "147573952589676410000.0"]
[68, "295147905179352830000.0"]
[69, "590295810358705700000.0"]
[70, "1180591620717411300000.0"]
[71, "2361183241434822600000.0"]
[72, "4722366482869645000000.0"]
[73, "9444732965739290000000.0"]
[74, "18889465931478580000000.0"]
[75, "37778931862957160000000.0"]
[76, "75557863725914320000000.0"]
[77, "151115727451828650000000.0"]
[78, "302231454903657300000000.0"]
[79, "604462909807314600000000.0"]
[80, "1208925819614629200000000.0"]
[81, "2417851639229258300000000.0"]
[82, "4835703278458517000000000.0"]
[83, "9671406556917033000000000.0"]
[84, "19342813113834067000000000.0"]
[85, "38685626227668134000000000.0"]
[86, "77371252455336270000000000.0"]
[87, "154742504910672530000000000.0"]
[88, "309485009821345100000000000.0"]
[89, "618970019642690200000000000.0"]
[90, "1237940039285380300000000000.0"]
[91, "2475880078570760500000000000.0"]
[92, "4951760157141521000000000000.0"]
[93, "9903520314283042000000000000.0"]
[94, "19807040628566084000000000000.0"]
[95, "39614081257132170000000000000.0"]
[96, "79228162514264340000000000000.0"]
[97, "158456325028528680000000000000.0"]
[98, "316912650057057350000000000000.0"]
[99, "633825300114114700000000000000.0"]
[100, "1267650600228229400000000000000.0"]
[101, "2535301200456459000000000000000.0"]
[102, "5070602400912918000000000000000.0"]
[103, "10141204801825835000000000000000.0"]
[104, "2.028240960365167e+31"]
...
[200, "1.6069380442589903e+60"]

この例では、(1 << 55).to_f から (1 << 103).to_f で、整数部分の
下のほうの桁が 0 になっています。

(1 << n) の整数部最下位桁は 0 にはならないので、これはまちがっています。

おそらく、そういう間違った桁を表示するようになってしまう状況では
指数形式を使って、そのあたりの桁は表示しないようにするべきなのだと思います。

また、実際、1.8.7 ではそのように動作します。

% ruby-1.8.7p370 -ve '1.upto(200) {|i| p [i, (1 << i).to_f.to_s] }'
ruby 1.8.7 (2012-06-29 patchlevel 370) [x86_64-linux]
[1, "2.0"]
[2, "4.0"]
...
[46, "70368744177664.0"]
[47, "1.40737488355328e+14"]
...

Actions

Also available in: Atom PDF

Like0
Like0