Пример #1
0
 /**
  * Raise e to the power of this.
  * @param number $precision the precision we want to return this to (default = DEFAULT_PRECISION).
  * @return BigNumber e raised to the power of *this.
  */
 public function Exp($precision = self::BIGNUMBER_DEFAULT_PRECISION)
 {
     // shortcut
     if ($this->IsZero()) {
         // reset this to 1
         $this->_Copy(BigNumberConstants::One());
         //  done
         return $this->PerformPostOperations($precision);
     }
     // get the integer part of the number.
     $integer = (new BigNumber($this))->Integer();
     // now get the decimal part of the number
     $fraction = (new BigNumber($this))->Frac();
     // reset 'this' to 1
     $this->_Copy(BigNumberConstants::One());
     // the two sides of the equation
     // the whole number.
     if (!$integer->IsZero()) {
         // get the value of e
         $e = BigNumberConstants::e();
         // truncate the precision so we do not do too many multiplications.
         // add a bit of room for more accurate precision.
         $e->Trunc(BigNumberConstants::PrecisionPadding($precision));
         //  then raise it.
         $this->_Copy($e->Pow($integer, BigNumberConstants::PrecisionPadding($precision)));
     }
     if (!$fraction->IsZero()) {
         //     x^1   x^2   x^3
         // 1 + --- + --- + --- ...
         //      1!    2!    3!
         $fact = BigNumberConstants::One();
         $base = new BigNumber($fraction);
         $power = new BigNumber($base);
         $result = BigNumberConstants::One();
         $paddedPrecision = BigNumberConstants::PrecisionPadding($precision);
         for ($i = 1; $i < self::BIGNUMBER_MAX_EXP_ITERATIONS; ++$i) {
             //  calculate the number up to the precision we are after.
             $calulatedNumber = (new BigNumber($power))->Div($fact, $paddedPrecision);
             if ($calulatedNumber->IsZero()) {
                 break;
             }
             // add it to our number.
             $result->Add($calulatedNumber);
             // x * x * x ...
             $power->Mul($base, $paddedPrecision);
             //  1 * 2 * 3 ...
             $fact->Mul((int) ($i + 1), $paddedPrecision);
         }
         //  the decimal part of the number.
         $fraction = $result;
         // multiply the decimal number with the fraction.
         $this->Mul($fraction, BigNumberConstants::PrecisionPadding($precision));
     }
     // clean up and return.
     return $this->PerformPostOperations($precision);
 }