/********************************************
libmawk (C) 2009-2014, Tibor 'Igor2' Palinkas;

This is a source file for libmawk, an implementation of
the AWK programming language, fork of mawk.

Libmawk is distributed without warranty under the terms of
the GNU General Public License, version 2, 1991.
********************************************/

#include "mawk.h"
#include "num.h"

const mawk_num_id_t mawk_num_id = MAWK_NUM_ID_INT;

/* convert a number to Int; Int is int */

Int mawk_d_to_I(mawk_num_t d)
{
	return (Int) d;
}

const char *mawk_num_print_spec(mawk_num_t d)
{
	if (P_isnan(d))
		return "nan";
	return NULL;
}

/* slow implementstion */
mawk_num_t mawk_num_pow(mawk_num_t x, mawk_num_t y)
{
	mawk_num_t a = 1;

	for(; y > 0; y--)
		a = a * x;
	return a;
}


#define abs_macro(x) ((x) < 0 ? -(x) : (x))

mawk_num_t mawk_num_sqrt(mawk_num_t x)
{
	mawk_num_t old_guess, guess;
	if (P_isnan(x) || (x == 0))
		return x;
	if (x < 0)
		return P_nan();

/* Babylonian method */
	guess = 1;
	old_guess = -1;
	while(abs_macro(old_guess - guess) > 1) {
		old_guess = guess;
		guess = (guess + x/guess) / 2;
	}
	return guess;
}
