[PATCH] manual: logb(x) is floor(log2(fabs(x)))

Vincent Lefevre vincent@vinc17.net
Tue Mar 5 10:02:51 GMT 2024


On 2024-03-04 23:40:59 +0100, Alejandro Colomar wrote:
> log2(3) doesn't accept negative input, but it seems logb(3) does
> accept it.

Yes, but unrelated to that, there was an issue with the text before.

> Link: <https://lore.kernel.org/linux-man/ZeYKUOKYS7G90SaV@debian/T/#u>
> Reported-by: Morten Welinder <mwelinder@gmail.com>
> Cc: Adhemerval Zanella Netto <adhemerval.zanella@linaro.org>
> Signed-off-by: Alejandro Colomar <alx@kernel.org>
> ---
>  manual/math.texi | 2 +-
>  1 file changed, 1 insertion(+), 1 deletion(-)
> 
> diff --git a/manual/math.texi b/manual/math.texi
> index 2f6ee253b9..bf4027c4ee 100644
> --- a/manual/math.texi
> +++ b/manual/math.texi
> @@ -561,7 +561,7 @@ These functions return the base-2 logarithm of @var{x}.
>  @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
>  These functions extract the exponent of @var{x} and return it as a
>  floating-point value.  If @code{FLT_RADIX} is two, @code{logb} is equal
> -to @code{floor (log2 (x))}, except it's probably faster.
> +to @code{floor (log2 (fabs ((x)))}, except it's probably faster.

No, it isn't necessarily equal. The code floor (log2 (fabs ((x)))
can give an incorrect result due to rounding if x is just before
a power of 2, in particular if x is large.

#include <stdio.h>
#include <float.h>
#include <math.h>

int main (void)
{
  double x = DBL_MAX;

  printf ("x = %a\n", x);
  printf ("%a\n", log2 (fabs (x)));
  printf ("%a\n", floor (log2 (fabs (x))));
  printf ("%a\n", logb (x));
  return 0;
}

outputs

x = 0x1.fffffffffffffp+1023
0x1p+10
0x1p+10
0x1.ff8p+9

on an x86_64 machine.

-- 
Vincent Lefèvre <vincent@vinc17.net> - Web: <https://www.vinc17.net/>
100% accessible validated (X)HTML - Blog: <https://www.vinc17.net/blog/>
Work: CR INRIA - computer arithmetic / AriC project (LIP, ENS-Lyon)


More information about the Libc-alpha mailing list