[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
**Subject**: **Should not integer exponentiation work when it works?**
**From**: Dirk Laurie <dirk.laurie@...>
**Date**: Thu, 9 Jun 2016 10:45:34 +0200

I know I am reopening an old can of worms.
I find that need to code something the following quite often.
n=327 -- some integer calculated earlier
u = 2*n+1
v = u*u
simply because
v=(2*n+1)^2
returns a float. It feels as if I am programming in some low-level
language where intermediates must be stored explicilty. I am doing
the work that the compiler should do.
More seriously, there may occur mathematically wrong results when
it is not necessary.
> 37^12%37
16.0
Some alternatives are:
1. v=math.floor((2*n+1)^2) -- no warning of precison loss
2. v=ipow(2*n+1,2) for some user-written ipow(n,p) that falls back to
floating n^p if
(a) n and p are not both integers
(b) p<0
(c) the exponentiation operation overflows the integers.
3. v=(2*n+1)[2] after doing debug.setmetatable(1,{__index=ipow})
The last is not always terribly readable, e,g,
> (37)[12]%37
0
Would it not be nice if 37^12 returned 6582952005840035281?
I'm not asking that an integer exponent always calls a different
algorithm, only that when integer^n with integer n>=0 can be
represented exactly, that exact result will be provided.
One difficulty is that ipow is not easy to write. We are multiplying
large numbers in the process, e.g
> 69343957*3512479453921
3761551257857134389
In base 10, you can see the result is wrong (the last digit should
be a 7) so there must have been an overflow, but is there a cheap,
elegant way to detect it?