From e2a4969440dc77c7acfc5cab0ff7222816b5bef9 Mon Sep 17 00:00:00 2001 From: danogentili Date: Fri, 29 Jul 2016 21:19:51 +0200 Subject: [PATCH] Added sqrt function and tests for it. Also added two() function to return a BigInteger of value 2. --- src/BigDecimal.php | 42 +++++++++++++++++++++++++++ src/Exception/IsNegativeException.php | 23 +++++++++++++++ tests/BigDecimalTest.php | 9 +++--- 3 files changed, 69 insertions(+), 5 deletions(-) create mode 100644 src/Exception/IsNegativeException.php diff --git a/src/BigDecimal.php b/src/BigDecimal.php index ff004f7..d5a76ab 100644 --- a/src/BigDecimal.php +++ b/src/BigDecimal.php @@ -112,6 +112,22 @@ final class BigDecimal extends BigNumber implements \Serializable return $one; } + /** + * Returns a BigDecimal representing two, with a scale of zero. + * + * @return BigDecimal + */ + public static function two() + { + static $two = null; + + if ($two === null) { + $two = new BigDecimal('2'); + } + + return $two; + } + /** * Returns a BigDecimal representing ten, with a scale of zero. * @@ -413,6 +429,32 @@ final class BigDecimal extends BigNumber implements \Serializable return [$quotient, $remainder]; } + /** + * Returns the square root of this number. + * + * The quotient has a scale of `0`, and the remainder has a scale of `0`. + * + * @return BigDecimal With the square root of this number. + * + * @throws IsNegativeException If this number is negative. + */ + public function sqrt() + { + if ($this->isNegative()) { + throw IsNegativeException::isNegative($this); + } + $two = BigDecimal::two(); + $guess = $this->quotient($two); + while (true) { + $last = $guess; + $guess = $this->quotient($guess)->add($guess)->quotient($two); + // (($n / $guess) + $guess) / 2; + if($last->compareTo($guess) == 0) { + break; + } + } + return $guess; + } /** * Returns a BigDecimal with the current value and the specified scale. diff --git a/src/Exception/IsNegativeException.php b/src/Exception/IsNegativeException.php new file mode 100644 index 0000000..3d72cdc --- /dev/null +++ b/src/Exception/IsNegativeException.php @@ -0,0 +1,23 @@ +quotient(0); } + + /** * @expectedException \Brick\Math\Exception\DivisionByZeroException @@ -1368,12 +1370,9 @@ class BigDecimalTest extends AbstractTestCase BigDecimal::of(1.2)->remainder(0); } - /** - * @expectedException \Brick\Math\Exception\DivisionByZeroException - */ - public function testQuotientAndRemainderOfZeroThrowsException() + public function testsqrt() { - BigDecimal::of(1.2)->quotientAndRemainder(0); + $this->assertSame(BigDecimal::of(625)->sqrt(), BigDecimal::of(25)); } /**