lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

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


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

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

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

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?