sqrtl.c 1.37 KB
Newer Older
1 2 3
/* Emulation for sqrtl.
   Contributed by Paolo Bonzini

4
   Copyright 2002, 2003, 2007, 2009, 2010 Free Software Foundation, Inc.
5 6 7

   This file is part of gnulib.

8
   This program is free software: you can redistribute it and/or modify
Paul Eggert's avatar
Paul Eggert committed
9
   it under the terms of the GNU General Public License as published by
10 11
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.
12

Paul Eggert's avatar
Paul Eggert committed
13 14 15 16
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
17

18 19
   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20

21 22 23
#include <config.h>

/* Specification.  */
24 25
#include <math.h>

26
#include <float.h>
27 28 29

/* A simple Newton-Raphson method. */
long double
Bruno Haible's avatar
Bruno Haible committed
30
sqrtl (long double x)
31 32 33 34
{
  long double delta, y;
  int exponent;

35 36 37 38
  /* Check for NaN */
  if (isnanl (x))
    return x;

39 40
  /* Check for negative numbers */
  if (x < 0.0L)
Bruno Haible's avatar
Bruno Haible committed
41
    return (long double) sqrt (-1);
42

43 44
  /* Check for zero and infinites */
  if (x + x == x)
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
    return x;

  frexpl (x, &exponent);
  y = ldexpl (x, -exponent / 2);

  do
    {
      delta = y;
      y = (y + x / y) * 0.5L;
      delta -= y;
    }
  while (delta != 0.0L);

  return y;
}