develooper Front page | perl.perl6.users | Postings from April 2021

Accurate conversion of Num to Rat (and comparing Num and Rat)

Thread Next
April 6, 2021 01:09
Accurate conversion of Num to Rat (and comparing Num and Rat)
Message ID:

With perl5 (configured with $Config{nvtype} of "double") we can get a
rational expression of the exact value held (for example) by the double 0.1
by doing:

$ perl -e 'printf "%.60g\n", 1.0e-1;'

How can we achieve the same in raku ?

I tried:

$ raku -e 'printf "%.60g\n", 1.0e-1;'


$ raku -e 'say sprintf "%.60g", 1.0e-1;'
$ raku -e "say sprintf '<%.60g>', 1.0e-1;"

I asked about this and other issues on perlmonks (
The "other issues" have been resolved in that thread, but (currently) not
this issue.

One other thing (which I believe I understand, but find to be odd) is that
raku asserts that the rational value 1/10 is equivalent to the double 0.1e0:

> say 1/10 == 0.1e0

I can see that for some (but not all) intents and purposes one might as
well consider a rational value to be equivalent to a double if (and only
if) the specified rational value rounds to the specified double value.
That's ok for interval arithmetic, but I don't think we're doing interval
arithmetic here.
And I don't think the "==" operator is the appropriate operator to be using
for such a comparison.

For example, it seems that raku regards the double 0.5 as representing a
non-precise value in the range 2**-1 plus or minus 2**-54 (ie the double
0.5 plus or minus 0.5ULP).
So we see:

> say 1/2 == 0.5e0
> say (2 ** -1 + 2 ** -54).nude
(9007199254740993 18014398509481984)
> say 9007199254740993/18014398509481984 == 0.5e0

This raku behaviour is also at odds with the mpfr library's mpfr_cmp_q()
library which will assert that 1/10 is not equivalent to the double 0.1,
and that 9007199254740993/18014398509481984 is not equivalent to the double

Is there behaviour in other languages (eg python ?) that supports this
approach that raku has taken ?
Is there some raku documentation that discusses/elaborates/explains the
approach taken ?


Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About