On 02.02.2016 15:57, Kenny McCormack wrote:
> In article <n8qfbh$4up$
1...@news.m-online.net>,
> Janis Papanagnou <
janis_pa...@hotmail.com> wrote:
>> On 02.02.2016 15:37, Kenny McCormack wrote:
>>> My versions of GAWK have GMP/MPFR compiled in, but I have to admit that I
>>> don't really know how to use it. I won't go into details, but I found the
>>> sections in the GAWK documentation cryptic at best.
>>>
>>> Here's my basic problem: I want to calculate and display 2^^61 - 1.
>>>
>>> Here's the basic idea in GAWK:
>>>
>>> $ gawk4 '{ OFMT="%.30g";print 2**$1-1 }'
>>> 61
>>> 2305843009213693952
>>> ^C
>>> $
>>>
>>> Well, this is obviously wrong, since we know the result should be odd.
>>>
>>> Is it possible to get the right result, using GMP/MPFR (in GAWK) ?
>>>
>>
>> $ gawk -M '{ OFMT="%.30g";print 2**$1-1 }'
>> 61
>> 2305843009213693951
>> 10
>> 1023
>> 99
>> 633825300114114700748351602687
>
> Interesting.
Frankly, I'm quite scared about the effect that omitting -M will produce
(off-by-one?) results. That's a subtle effect, and (if not having -M as
default) an error message would be more what I'd expect.[*]
> So, that's all you have to do?
That's the thing I memorized about gawk's MP-arithmetic. And the option
to explicitly define the precision using the variable PREC.
>
> Somehow, the description in the dox makes it sound like you have to do a
> lot more faffling about to get the right answers.
>
> A few other comments/questions:
>
> 1) One wonders why it isn't the default? Why *should* we have to
> remember to put in "-M" ?
Can't tell. Maybe the visible design effect of some internal optimization?
>
> 2) FWIW, ISTM that you don't need the OFMT stuff now, if you are using
> "-M".
>
> 3) How do I turn "-M" mode on from within a GAWK source file?
> I.e., just as we can use things like "-i" and "-l" on the command
> line, or we can us "@include" or "@load" inside the source code, is
> there a similar trick to use inside the code to turn on "-M" mode?
While I seem to recall to have done something like that (using @load) in
the past I'm not sure now (and too lazy to check the documents); maybe it
has been removed in recent versions, or maybe I was just misremembering.
Janis
[*] Actually since I noticed many years ago that even the bc command will
silently produce wrong results (depending on the precision used)[**] I'm
very reluctant to use MP in any tool without double checking the results.
[**] I seem to recall that POSIX guarantees only 99 digits accuracy, but
larger results are accepted (e.g. in GNU's bc), but correct [only] until
some margin; no error messages there either. (Don't know if that has ever
been fixed.)