/bin/sh and BIG NUMBERS

Dan Nelson dnelson at allantgroup.com
Sun Apr 6 19:49:23 PDT 2003


In the last episode (Apr 06), Mikko Ty?l?j?rvi said:
> On Sun, 6 Apr 2003, Bill Vermillion wrote:
> > On Sun, Apr 06, 2003 at 12:00 ,
> > > On 2003-04-05 07:06, Alex Semenyaka <alexs at ratmir.ru> wrote:
> > > > I found that /bin/sh cannot handle numbers those do not fit to
> > > > integer type.  That is not too bad. Too bad that it just
> > > > silently warps them in arithmetical operations:
> >
> > > > alexs at snark> /bin/sh -c 'echo $((10000000000-1))'
> > > > 2147483646
> >
> > Not all shells have that problem.  I'm using the real KSH from AT&T
> > via the ports.  It's returns 999999999 quite nicely :-)
> 
> Ksh seems to use floats for calculations, and so instead silently
> drops precision when dealing with sufficiently large numbers:
> 
>  atlas% ksh93 -c 'echo $((10000000000002-1))'
>  1e+13
> 
> Zsh uses 64 bit ints, which silently overflow, albeit at larger values
> than FreeBSD's sh(1).  The same goes for bash.
> 
> Looks like shells aren't the best environment for bignum arithmetic :^)

You could always rewrite libgmp as a set of shell functions :)

POSIX requirements for math in shells are pretty lenient:

  * Only signed long integer arithmetic is required.

  As an extension, the shell may recognize arithmetic expressions
  beyond those listed. The shell may use a signed integer type with a
  rank larger than the rank of signed long. The shell may use a
  real-floating type instead of signed long as long as it does not
  affect the results in cases where there is no overflow.

-- 
	Dan Nelson
	dnelson at allantgroup.com


More information about the freebsd-hackers mailing list