Replies: 5 comments 16 replies
-
This happens because 4.1 is represented as 4.099... (as per https://www.h-schmidt.net/FloatConverter/IEEE754.html) and it messes-up with an algorithm. |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
The conversion from E notation could be done in Rust.
|
Beta Was this translation helpful? Give feedback.
-
Here's my attempt at it: get_two_exponent(N10, N2) :-
% 10 ^ (3*N10) ~= 2 ^ (10*N2)
% -> 10 ^ N10 ~= 2 ^ (10*N2/3)
% The + 5 is for good measure, and there's otherwise no need to go above 53 bits.
N2 is min(ceiling(N10) * 10 // 3 + 5, 53).
format_float3(F, N) -->
{
Int is truncate(F),
Frac is abs(float_fractional_part(F)),
get_two_exponent(N, N2),
TwoPow is 2 ^ N2,
FracInt is floor(Frac * TwoPow),
N1 is N + 1,
fractional_part_to_int(FracInt, TwoPow, N1, FracInt10),
FracIntRounded is round(FracInt10 rdiv 10)
},
( { Int = 0, F < 0, FracInt > TwoPow } -> "-0" ; { number_chars(Int, Is) }, seq(Is) ),
".",
format_float_fractional_part(FracIntRounded, N).
fractional_part_to_int(F, B, N, Out) :-
N > 0,
N1 is N - 1,
F10 is F * 10,
NextF is F10 mod B,
Digit is F10 // B,
fractional_part_to_int(NextF, B, N1, Prev),
Out is Prev + Digit * 10 ^ N1.
fractional_part_to_int(_, _, 0, 0).
format_float_fractional_part(I, N) -->
{
N > 0,
N1 is N - 1,
Digit is I // 10 ^ N1,
NextI is I mod 10 ^ N1,
number_chars(Digit, Ds)
},
seq(Ds),
format_float_fractional_part(NextI, N1).
format_float_fractional_part(_, 0) --> []. |
Beta Was this translation helpful? Give feedback.
-
Also we need to decide first what do we mean by "correct" string representation. I would argue that the important property is reading it back should yield exactly the same number up to rounding factor. Another also "correct" representation would be actual value that is stored. |
Beta Was this translation helpful? Give feedback.
-
Dear all,
trying to address #2771, I came up with the following code to relate a float to decimal digits represented as a list of characters:
Thanks to the great recent improvements to
truncate/1
and related features by @adri326 in #2777, this seems to solve the concrete issue nicely:It also works nicely for several other cases, such as:
However, the logic unfortunately falls short in cases like the following:
I would greatly appreciate any help with this!
Thank you a lot,
Markus
Beta Was this translation helpful? Give feedback.
All reactions