updating sqrt to work with doubles
This commit is contained in:
@@ -133,7 +133,7 @@ int ft_fsign(double i);
|
|||||||
double ft_modf(double x, double *int_part);
|
double ft_modf(double x, double *int_part);
|
||||||
double ft_pow(double base, int exponent);
|
double ft_pow(double base, int exponent);
|
||||||
double ft_round(double x);
|
double ft_round(double x);
|
||||||
int ft_sqrt(int i);
|
double ft_sqrt(double i);
|
||||||
void ft_free_tab(char **tab);
|
void ft_free_tab(char **tab);
|
||||||
|
|
||||||
int ft_arrint(int *intarr, int comp, size_t size);
|
int ft_arrint(int *intarr, int comp, size_t size);
|
||||||
|
|||||||
@@ -1,15 +1,41 @@
|
|||||||
#include "libft.h"
|
#include "libft.h"
|
||||||
|
|
||||||
/*
|
/*
|
||||||
** return the square root of nb
|
* return the square root of nb
|
||||||
** or the integer value of it
|
* Newton–Raphson method : https://en.wikipedia.org/wiki/Newton%27s_method#Use_of_Newton's_method_to_compute_square_roots
|
||||||
*/
|
*/
|
||||||
int ft_sqrt(int nb)
|
double ft_sqrt(double x)
|
||||||
{
|
{
|
||||||
int i;
|
double precision;
|
||||||
|
|
||||||
i = 0;
|
if (x < 0)
|
||||||
while ((i*i) < nb)
|
return -1; // handle negative numbers
|
||||||
i++;
|
if (x == 0)
|
||||||
return (i);
|
return 0;
|
||||||
|
|
||||||
|
precision = 0.00001;
|
||||||
|
|
||||||
|
// Newton-Raphson
|
||||||
|
double guess = x;
|
||||||
|
double prev_guess;
|
||||||
|
do
|
||||||
|
{
|
||||||
|
prev_guess = guess;
|
||||||
|
guess = (guess + x / guess) / 2.0;
|
||||||
|
} while (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;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
#include "libft.h"
|
#include "libft.h"
|
||||||
|
|
||||||
/*
|
// /*
|
||||||
** return the square root of nb
|
// ** return the square root of nb
|
||||||
** or the integer value of it
|
// ** or the integer value of it
|
||||||
*/
|
// */
|
||||||
int ft_sqrt(int nb)
|
// int ft_sqrt(int nb)
|
||||||
{
|
// {
|
||||||
int i;
|
// int i;
|
||||||
|
|
||||||
i = 0;
|
// i = 0;
|
||||||
while ((i*i) < nb)
|
// while ((i*i) < nb)
|
||||||
i++;
|
// i++;
|
||||||
return (i);
|
// return (i);
|
||||||
}
|
// }
|
||||||
|
|||||||
Reference in New Issue
Block a user