Decimal floating point number to binary: Difference between revisions
Content added Content deleted
m (→{{header|Phix}}: simplified output) |
m (→{{header|Phix}}: added limiter) |
||
Line 1,081: | Line 1,081: | ||
if d>0 then |
if d>0 then |
||
res &= '.' |
res &= '.' |
||
-- while d>0 do -- (see update below) |
|||
while d>0 |
|||
and (base=2 or length(res)<15) do |
|||
d *= base |
d *= base |
||
integer digit = floor(d) |
integer digit = floor(d) |
||
Line 1,114: | Line 1,116: | ||
procedure test(atom f, integer base=2) |
procedure test(atom f, integer base=2) |
||
string s = dec_to(f,base) |
string s = dec_to(f,base) |
||
atom g = to_dec(s,base) |
atom g = to_dec(s,base), |
||
h = f-g |
|||
⚫ | |||
string e = iff(h=0?"":sprintf(" (error: %g)",h)) |
|||
⚫ | |||
end procedure |
end procedure |
||
test(23.34375) |
test(23.34375) |
||
Line 1,141: | Line 1,145: | ||
0 => 0(2):0 => 0 |
0 => 0(2):0 => 0 |
||
65535 => 0(16):FFFF => 65535 |
65535 => 0(16):FFFF => 65535 |
||
23.7 => 0(35):N.OHHHHHHHHFIVE => 23.7 (error: -3.55271e-15) |
|||
23.7 |
23.7 |
||
"23.699999999999" |
|||
"23.699999999999999289457264239899814128875732421875" |
|||
</pre> |
</pre> |
||
Aside: I was quite surprised to get 100% accuracy on these tests, but actually it is more of |
Aside: I was quite surprised to get 100% accuracy on these tests, but actually it is more of |
||
a lucky coincidence in the way it is written, as the last test shows. The truth of the matter |
a lucky coincidence in the way it is written, as the last test shows. The truth of the matter |
||
is simply that you ''can'' extract a float to a binary text representation exactly, in a way that |
is simply that you ''can'' extract a float to a binary text representation exactly, in a way that |
||
you just cannot do for most other (ie non-power-2) bases. |
you just cannot do for most other (ie non-power-2) bases.<br> |
||
Update: Added a limiter for non-base-2 fractions, as per 1/3 -> 0.333 forever in decimal. Base 2 is guaranteed to |
|||
terminate anyway, but for other bases we need some limit - the 15 I opted for is completely arbitrary. |
|||
=={{header|Python}}== |
=={{header|Python}}== |