Saturday, October 4, 2008

Nth Root

Both ASP and PHP have a function that allows you to calculate the square root of a number. What if we wanted the cubic root of a number, or some deeper root? Calculating the root of a number is the same as raising that number to a fractional exponent.


ASP

  1. function root(x, y)
  2.     root = x ^ (1 / y)
  3. end function

PHP

  1. function root($x, $y)
  2. {
  3.     return pow($x, 1/$y);
  4. }

x
the number you want the root of
y
the depth you want to go (2 = square, 3 = cubic, etc.)

2 comments:

Raise said...

No idea about ASP, but your PHP example is wrong. ^ is the bitwise XOR operator in PHP.

This is what you want:

public function nth_root($x, $y)
{
return pow($x, 1/$y);
}

Scott said...

Thanks, I've updated the example.