Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: print and floating point output



Matthias Kopfermann wrote:
> print $((2.8*16.0))
> which _sadly_, i think, returns:
> 44.799999999999997
> 
> I wonder if it really was a good decision to print so many numbers
> after the point.

Well, the alternative is silently censoring decimal places, many of
which may be valid.  If you want something smart to guess how many
places are valid, you need to write it.

Use

  typeset -F 8 var

or

  typeset -E 8 var

then

  (( var = 2.8 * 16.0 ))
  print $var

for a given number of decimal places.  Or use printf, which does it's
own conversion:

% printf "%f\n" $((2.8*16.0))
44.800000

What you're really asking for is zsh to `guess' that the accuracy is one
place, or a few places less.  A little playing around with chains of
multiplications will soon so that this isn't a particularly good
solution.

If you are doing serious floating point work, unfortunately you need to
understand something about rounding errors, which are a tricky and
ever-present feature.

-- 
Peter Stephenson <pws@xxxxxxx>                  Software Engineer
CSR Ltd., Science Park, Milton Road,
Cambridge, CB4 0WH, UK                          Tel: +44 (0)1223 692070


**********************************************************************
This email and any files transmitted with it are confidential and
intended solely for the use of the individual or entity to whom they
are addressed. If you have received this email in error please notify
the system manager.

This footnote also confirms that this email message has been swept by
MIMEsweeper for the presence of computer viruses.

www.mimesweeper.com
**********************************************************************



Messages sorted by: Reverse Date, Date, Thread, Author