[ create a new paste ] login | about

Link: http://codepad.org/LRVEMHTg    [ raw code | output | fork ]

PHP, pasted on May 9:
<?php

function _pow($n, $exp)
{
	$result = pow($n, intval($exp)); // bcmath casts $exp to (int)

	if (fmod($exp, 1) > 0) // does $exp have a fracional part higher than 0?
	{
		$exp = 1 / fmod($exp, 1); // lets convert the fracional part into a root (2.5 -> 1 / 0.5 = 2)

		$x = 1;
		$y = (($n * _pow($x, 1 - $exp)) / $exp) - ($x / $exp) + $x;

		do
		{
			$x = $y;
			$y = (($n * _pow($x, 1 - $exp)) / $exp) - ($x / $exp) + $x;
		} while ($x > $y);

		return $result * $x; // 4^2.5 = 4^2 * 4^0.5 = 16 * 2 = 32
	}
	
	return $result;
}

var_dump(_pow(2, 0.5)); // 1.4142135623731
var_dump(_pow(2, 2.5)); // 5.6568542494924
var_dump(_pow(4, 0.5)); // 2
var_dump(_pow(4, 2.5)); // 32
var_dump(_pow(4, 1 / 3)); // 1.5874010519682

?>


Output:
1
2
3
4
5
float(1.4142135623731)
float(5.6568542494924)
float(2)
float(32)
float(1.5874010519682)


Create a new paste based on this one


Comments: