Files
42_INT_01_libft/srcs/ft_sqrt.c
2026-06-05 12:10:13 +02:00

38 lines
756 B
C
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "libft.h"
/*
* return the square root of nb
* NewtonRaphson method : https://en.wikipedia.org/wiki/Newton%27s_method#Use_of_Newton's_method_to_compute_square_roots
*/
double ft_sqrt(double x, double precision)
{
if (x < 0)
return -1; // handle negative numbers
if (x == 0)
return 0;
// Newton-Raphson
double guess = x;
double prev_guess;
do
{
prev_guess = guess;
guess = (guess + x / guess) / 2.0;
} while (ft_fabs(prev_guess - guess) > precision);
return guess;
// // binary search
// double low = 0;
// double high = x;
// double mid;
// while (high - low > precision)
// {
// mid = (low + high) / 2.0;
// if (mid * mid < x)
// low = mid;
// else
// high = mid;
// }
// return (low + high) / 2.0;
}