bug-gnulib
[Top][All Lists]
Advanced

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

Re: ftoastr vs. sprintf


From: Bruno Haible
Subject: Re: ftoastr vs. sprintf
Date: Thu, 18 Nov 2010 22:16:52 +0100
User-agent: KMail/1.9.9

Hi Jim,

> Before I'd looked through the code I started thinking this might
> be useful in avoiding snprintf's unhealthy need to malloc.

In fact, ftoastr and snprintf use different specifications and produce
different results. Basically, for *printf there's
  a) the fixed-point notation that has a number of digits that is
     essentially proportional to the absolute value of the exponent
     relative to base 10,
  b) the exponential notation that has a number of digits that
     does not depend on the precise value. That is, for any x in
     the interval  10^k <= x <= 9 * 10^k, the number of digits
     in the result is the same. Except that trailing zeroes are
     removed from the result.

Whereas the ftoastr function, and the print function from Scheme
and from Common Lisp earlier, produce
  c) a number of digits that is specifically tailored to the number
     being printed.
Do this in Common Lisp:

> (dotimes (i 20) (let ((x (random 1f0))) (when (>= x 0.1) (print x))))

0.46878344 
0.39263618 
0.22078264 
0.79339415 
0.4674837 
0.57952684 
0.5128485 
0.16842127 
0.40345955 
0.79092646 
0.699633 
0.7427649 
0.64850986 
0.2423734 
0.97288597 
0.619959 
0.61149883 
0.95406294 
0.76368487 
0.7692351 

> (dotimes (i 20) (let ((x (random 1d0))) (when (>= x 0.1) (print x))))

0.2701986644889345d0 
0.18110356102302427d0 
0.43414385354439977d0 
0.3499075309510783d0 
0.7577956910012907d0 
0.3948907291391772d0 
0.5045451713770114d0 
0.4242204029548028d0 
0.6656658009913122d0 
0.3674246830169696d0 
0.24062354408695663d0 
0.9909290642214384d0 
0.8406297437829119d0 
0.40724941267335724d0 
0.5902063407691376d0 
0.8576067558258175d0 
0.24526658689439673d0 
0.2978864010205464d0 

You see that the number of 'float' digits is sometimes 7 and sometimes 8,
and the number of 'double' digits is sometimes 16 and sometimes 17.

In other words, this algorithm removes also trailing *non-zero*
digits, when it is possible without changing the value of
(read-from-string result).

Different specifications require different algorithms.

Bruno



reply via email to

[Prev in Thread] Current Thread [Next in Thread]