PageRenderTime 114ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/branches/v1.7.2/Classes/PHPExcel/Calculation/Functions.php

#
PHP | 11480 lines | 6870 code | 1305 blank | 3305 comment | 2002 complexity | 02619cf6f0e9b2a50f9d61189a94a5ae MD5 | raw file
Possible License(s): AGPL-1.0, LGPL-2.0, LGPL-2.1, GPL-3.0, LGPL-3.0
  1. <?php
  2. /**
  3. * PHPExcel
  4. *
  5. * Copyright (c) 2006 - 2010 PHPExcel
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this library; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * @category PHPExcel
  22. * @package PHPExcel_Calculation
  23. * @copyright Copyright (c) 2006 - 2010 PHPExcel (http://www.codeplex.com/PHPExcel)
  24. * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  25. * @version ##VERSION##, ##DATE##
  26. */
  27. /** EPS */
  28. define('EPS', 2.22e-16);
  29. /** MAX_VALUE */
  30. define('MAX_VALUE', 1.2e308);
  31. /** LOG_GAMMA_X_MAX_VALUE */
  32. define('LOG_GAMMA_X_MAX_VALUE', 2.55e305);
  33. /** SQRT2PI */
  34. define('SQRT2PI', 2.5066282746310005024157652848110452530069867406099);
  35. /** 2 / PI */
  36. define('M_2DIVPI', 0.63661977236758134307553505349006);
  37. /** XMININ */
  38. define('XMININ', 2.23e-308);
  39. /** MAX_ITERATIONS */
  40. define('MAX_ITERATIONS', 256);
  41. /** FINANCIAL_MAX_ITERATIONS */
  42. define('FINANCIAL_MAX_ITERATIONS', 128);
  43. /** PRECISION */
  44. define('PRECISION', 8.88E-016);
  45. /** FINANCIAL_PRECISION */
  46. define('FINANCIAL_PRECISION', 1.0e-08);
  47. /** EULER */
  48. define('EULER', 2.71828182845904523536);
  49. $savedPrecision = ini_get('precision');
  50. if ($savedPrecision < 16) {
  51. ini_set('precision',16);
  52. }
  53. /** PHPExcel root directory */
  54. if (!defined('PHPEXCEL_ROOT')) {
  55. /**
  56. * @ignore
  57. */
  58. define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
  59. }
  60. /** PHPExcel_Cell */
  61. require_once PHPEXCEL_ROOT . 'PHPExcel/Cell.php';
  62. /** PHPExcel_Calculation */
  63. require_once PHPEXCEL_ROOT . 'PHPExcel/Calculation.php';
  64. /** PHPExcel_Cell_DataType */
  65. require_once PHPEXCEL_ROOT . 'PHPExcel/Cell/DataType.php';
  66. /** PHPExcel_Style_NumberFormat */
  67. require_once PHPEXCEL_ROOT . 'PHPExcel/Style/NumberFormat.php';
  68. /** PHPExcel_Shared_Date */
  69. require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/Date.php';
  70. /** Matrix */
  71. require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/JAMA/Matrix.php';
  72. require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/trendClass.php';
  73. /**
  74. * PHPExcel_Calculation_Functions
  75. *
  76. * @category PHPExcel
  77. * @package PHPExcel_Calculation
  78. * @copyright Copyright (c) 2006 - 2010 PHPExcel (http://www.codeplex.com/PHPExcel)
  79. */
  80. class PHPExcel_Calculation_Functions {
  81. /** constants */
  82. const COMPATIBILITY_EXCEL = 'Excel';
  83. const COMPATIBILITY_GNUMERIC = 'Gnumeric';
  84. const COMPATIBILITY_OPENOFFICE = 'OpenOfficeCalc';
  85. const RETURNDATE_PHP_NUMERIC = 'P';
  86. const RETURNDATE_PHP_OBJECT = 'O';
  87. const RETURNDATE_EXCEL = 'E';
  88. /**
  89. * Compatibility mode to use for error checking and responses
  90. *
  91. * @access private
  92. * @var string
  93. */
  94. private static $compatibilityMode = self::COMPATIBILITY_EXCEL;
  95. /**
  96. * Data Type to use when returning date values
  97. *
  98. * @access private
  99. * @var integer
  100. */
  101. private static $ReturnDateType = self::RETURNDATE_EXCEL;
  102. /**
  103. * List of error codes
  104. *
  105. * @access private
  106. * @var array
  107. */
  108. private static $_errorCodes = array( 'null' => '#NULL!',
  109. 'divisionbyzero' => '#DIV/0!',
  110. 'value' => '#VALUE!',
  111. 'reference' => '#REF!',
  112. 'name' => '#NAME?',
  113. 'num' => '#NUM!',
  114. 'na' => '#N/A',
  115. 'gettingdata' => '#GETTING_DATA'
  116. );
  117. /**
  118. * Set the Compatibility Mode
  119. *
  120. * @access public
  121. * @category Function Configuration
  122. * @param string $compatibilityMode Compatibility Mode
  123. * Permitted values are:
  124. * PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL 'Excel'
  125. * PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC 'Gnumeric'
  126. * PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc'
  127. * @return boolean (Success or Failure)
  128. */
  129. public static function setCompatibilityMode($compatibilityMode) {
  130. if (($compatibilityMode == self::COMPATIBILITY_EXCEL) ||
  131. ($compatibilityMode == self::COMPATIBILITY_GNUMERIC) ||
  132. ($compatibilityMode == self::COMPATIBILITY_OPENOFFICE)) {
  133. self::$compatibilityMode = $compatibilityMode;
  134. return True;
  135. }
  136. return False;
  137. } // function setCompatibilityMode()
  138. /**
  139. * Return the current Compatibility Mode
  140. *
  141. * @access public
  142. * @category Function Configuration
  143. * @return string Compatibility Mode
  144. * Possible Return values are:
  145. * PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL 'Excel'
  146. * PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC 'Gnumeric'
  147. * PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc'
  148. */
  149. public static function getCompatibilityMode() {
  150. return self::$compatibilityMode;
  151. } // function getCompatibilityMode()
  152. /**
  153. * Set the Return Date Format used by functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object)
  154. *
  155. * @access public
  156. * @category Function Configuration
  157. * @param string $returnDateType Return Date Format
  158. * Permitted values are:
  159. * PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC 'P'
  160. * PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT 'O'
  161. * PHPExcel_Calculation_Functions::RETURNDATE_EXCEL 'E'
  162. * @return boolean Success or failure
  163. */
  164. public static function setReturnDateType($returnDateType) {
  165. if (($returnDateType == self::RETURNDATE_PHP_NUMERIC) ||
  166. ($returnDateType == self::RETURNDATE_PHP_OBJECT) ||
  167. ($returnDateType == self::RETURNDATE_EXCEL)) {
  168. self::$ReturnDateType = $returnDateType;
  169. return True;
  170. }
  171. return False;
  172. } // function setReturnDateType()
  173. /**
  174. * Return the current Return Date Format for functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object)
  175. *
  176. * @access public
  177. * @category Function Configuration
  178. * @return string Return Date Format
  179. * Possible Return values are:
  180. * PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC 'P'
  181. * PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT 'O'
  182. * PHPExcel_Calculation_Functions::RETURNDATE_EXCEL 'E'
  183. */
  184. public static function getReturnDateType() {
  185. return self::$ReturnDateType;
  186. } // function getReturnDateType()
  187. /**
  188. * DUMMY
  189. *
  190. * @access public
  191. * @category Error Returns
  192. * @return string #Not Yet Implemented
  193. */
  194. public static function DUMMY() {
  195. return '#Not Yet Implemented';
  196. } // function DUMMY()
  197. /**
  198. * NA
  199. *
  200. * @access public
  201. * @category Error Returns
  202. * @return string #N/A!
  203. */
  204. public static function NA() {
  205. return self::$_errorCodes['na'];
  206. } // function NA()
  207. /**
  208. * NAN
  209. *
  210. * @access public
  211. * @category Error Returns
  212. * @return string #NUM!
  213. */
  214. public static function NaN() {
  215. return self::$_errorCodes['num'];
  216. } // function NAN()
  217. /**
  218. * NAME
  219. *
  220. * @access public
  221. * @category Error Returns
  222. * @return string #NAME!
  223. */
  224. public static function NAME() {
  225. return self::$_errorCodes['name'];
  226. } // function NAME()
  227. /**
  228. * REF
  229. *
  230. * @access public
  231. * @category Error Returns
  232. * @return string #REF!
  233. */
  234. public static function REF() {
  235. return self::$_errorCodes['reference'];
  236. } // function REF()
  237. /**
  238. * VALUE
  239. *
  240. * @access public
  241. * @category Error Returns
  242. * @return string #VALUE!
  243. */
  244. public static function VALUE() {
  245. return self::$_errorCodes['value'];
  246. } // function VALUE()
  247. private static function isMatrixValue($idx) {
  248. return ((substr_count($idx,'.') <= 1) || (preg_match('/\.[A-Z]/',$idx) > 0));
  249. }
  250. private static function isValue($idx) {
  251. return (substr_count($idx,'.') == 0);
  252. }
  253. private static function isCellValue($idx) {
  254. return (substr_count($idx,'.') > 1);
  255. }
  256. /**
  257. * LOGICAL_AND
  258. *
  259. * Returns boolean TRUE if all its arguments are TRUE; returns FALSE if one or more argument is FALSE.
  260. *
  261. * Excel Function:
  262. * =AND(logical1[,logical2[, ...]])
  263. *
  264. * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays
  265. * or references that contain logical values.
  266. *
  267. * Boolean arguments are treated as True or False as appropriate
  268. * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False
  269. * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds
  270. * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value
  271. *
  272. * @access public
  273. * @category Logical Functions
  274. * @param mixed $arg,... Data values
  275. * @return boolean The logical AND of the arguments.
  276. */
  277. public static function LOGICAL_AND() {
  278. // Return value
  279. $returnValue = True;
  280. // Loop through the arguments
  281. $aArgs = self::flattenArray(func_get_args());
  282. $argCount = 0;
  283. foreach ($aArgs as $arg) {
  284. // Is it a boolean value?
  285. if (is_bool($arg)) {
  286. $returnValue = $returnValue && $arg;
  287. } elseif ((is_numeric($arg)) && (!is_string($arg))) {
  288. $returnValue = $returnValue && ($arg != 0);
  289. } elseif (is_string($arg)) {
  290. $arg = strtoupper($arg);
  291. if ($arg == 'TRUE') {
  292. $arg = 1;
  293. } elseif ($arg == 'FALSE') {
  294. $arg = 0;
  295. } else {
  296. return self::$_errorCodes['value'];
  297. }
  298. $returnValue = $returnValue && ($arg != 0);
  299. }
  300. ++$argCount;
  301. }
  302. // Return
  303. if ($argCount == 0) {
  304. return self::$_errorCodes['value'];
  305. }
  306. return $returnValue;
  307. } // function LOGICAL_AND()
  308. /**
  309. * LOGICAL_OR
  310. *
  311. * Returns boolean TRUE if any argument is TRUE; returns FALSE if all arguments are FALSE.
  312. *
  313. * Excel Function:
  314. * =OR(logical1[,logical2[, ...]])
  315. *
  316. * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays
  317. * or references that contain logical values.
  318. *
  319. * Boolean arguments are treated as True or False as appropriate
  320. * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False
  321. * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds
  322. * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value
  323. *
  324. * @access public
  325. * @category Logical Functions
  326. * @param mixed $arg,... Data values
  327. * @return boolean The logical OR of the arguments.
  328. */
  329. public static function LOGICAL_OR() {
  330. // Return value
  331. $returnValue = False;
  332. // Loop through the arguments
  333. $aArgs = self::flattenArray(func_get_args());
  334. $argCount = 0;
  335. foreach ($aArgs as $arg) {
  336. // Is it a boolean value?
  337. if (is_bool($arg)) {
  338. $returnValue = $returnValue || $arg;
  339. } elseif ((is_numeric($arg)) && (!is_string($arg))) {
  340. $returnValue = $returnValue || ($arg != 0);
  341. } elseif (is_string($arg)) {
  342. $arg = strtoupper($arg);
  343. if ($arg == 'TRUE') {
  344. $arg = 1;
  345. } elseif ($arg == 'FALSE') {
  346. $arg = 0;
  347. } else {
  348. return self::$_errorCodes['value'];
  349. }
  350. $returnValue = $returnValue || ($arg != 0);
  351. }
  352. ++$argCount;
  353. }
  354. // Return
  355. if ($argCount == 0) {
  356. return self::$_errorCodes['value'];
  357. }
  358. return $returnValue;
  359. } // function LOGICAL_OR()
  360. /**
  361. * LOGICAL_FALSE
  362. *
  363. * Returns the boolean FALSE.
  364. *
  365. * Excel Function:
  366. * =FALSE()
  367. *
  368. * @access public
  369. * @category Logical Functions
  370. * @return boolean False
  371. */
  372. public static function LOGICAL_FALSE() {
  373. return False;
  374. } // function LOGICAL_FALSE()
  375. /**
  376. * LOGICAL_TRUE
  377. *
  378. * Returns the boolean TRUE.
  379. *
  380. * Excel Function:
  381. * =TRUE()
  382. *
  383. * @access public
  384. * @category Logical Functions
  385. * @return boolean True
  386. */
  387. public static function LOGICAL_TRUE() {
  388. return True;
  389. } // function LOGICAL_TRUE()
  390. /**
  391. * LOGICAL_NOT
  392. *
  393. * Returns the boolean inverse of the argument.
  394. *
  395. * Excel Function:
  396. * =NOT(logical)
  397. *
  398. * The argument must evaluate to a logical value such as TRUE or FALSE
  399. *
  400. * Boolean arguments are treated as True or False as appropriate
  401. * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False
  402. * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds
  403. * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value
  404. *
  405. * @access public
  406. * @category Logical Functions
  407. * @param mixed $logical A value or expression that can be evaluated to TRUE or FALSE
  408. * @return boolean The boolean inverse of the argument.
  409. */
  410. public static function LOGICAL_NOT($logical) {
  411. $logical = self::flattenSingleValue($logical);
  412. if (is_string($logical)) {
  413. $logical = strtoupper($logical);
  414. if ($logical == 'TRUE') {
  415. return False;
  416. } elseif ($logical == 'FALSE') {
  417. return True;
  418. } else {
  419. return self::$_errorCodes['value'];
  420. }
  421. }
  422. return !$logical;
  423. } // function LOGICAL_NOT()
  424. /**
  425. * STATEMENT_IF
  426. *
  427. * Returns one value if a condition you specify evaluates to TRUE and another value if it evaluates to FALSE.
  428. *
  429. * Excel Function:
  430. * =IF(condition[,returnIfTrue[,returnIfFalse]])
  431. *
  432. * Condition is any value or expression that can be evaluated to TRUE or FALSE.
  433. * For example, A10=100 is a logical expression; if the value in cell A10 is equal to 100,
  434. * the expression evaluates to TRUE. Otherwise, the expression evaluates to FALSE.
  435. * This argument can use any comparison calculation operator.
  436. * ReturnIfTrue is the value that is returned if condition evaluates to TRUE.
  437. * For example, if this argument is the text string "Within budget" and the condition argument evaluates to TRUE,
  438. * then the IF function returns the text "Within budget"
  439. * If condition is TRUE and ReturnIfTrue is blank, this argument returns 0 (zero). To display the word TRUE, use
  440. * the logical value TRUE for this argument.
  441. * ReturnIfTrue can be another formula.
  442. * ReturnIfFalse is the value that is returned if condition evaluates to FALSE.
  443. * For example, if this argument is the text string "Over budget" and the condition argument evaluates to FALSE,
  444. * then the IF function returns the text "Over budget".
  445. * If condition is FALSE and ReturnIfFalse is omitted, then the logical value FALSE is returned.
  446. * If condition is FALSE and ReturnIfFalse is blank, then the value 0 (zero) is returned.
  447. * ReturnIfFalse can be another formula.
  448. *
  449. * @access public
  450. * @category Logical Functions
  451. * @param mixed $condition Condition to evaluate
  452. * @param mixed $returnIfTrue Value to return when condition is true
  453. * @param mixed $returnIfFalse Optional value to return when condition is false
  454. * @return mixed The value of returnIfTrue or returnIfFalse determined by condition
  455. */
  456. public static function STATEMENT_IF($condition = true, $returnIfTrue = 0, $returnIfFalse = False) {
  457. $condition = (is_null($condition)) ? True : (boolean) self::flattenSingleValue($condition);
  458. $returnIfTrue = (is_null($returnIfTrue)) ? 0 : self::flattenSingleValue($returnIfTrue);
  459. $returnIfFalse = (is_null($returnIfFalse)) ? False : self::flattenSingleValue($returnIfFalse);
  460. return ($condition ? $returnIfTrue : $returnIfFalse);
  461. } // function STATEMENT_IF()
  462. /**
  463. * STATEMENT_IFERROR
  464. *
  465. * Excel Function:
  466. * =IFERROR(testValue,errorpart)
  467. *
  468. * @access public
  469. * @category Logical Functions
  470. * @param mixed $testValue Value to check, is also the value returned when no error
  471. * @param mixed $errorpart Value to return when testValue is an error condition
  472. * @return mixed The value of errorpart or testValue determined by error condition
  473. */
  474. public static function STATEMENT_IFERROR($testValue = '', $errorpart = '') {
  475. $testValue = (is_null($testValue)) ? '' : self::flattenSingleValue($testValue);
  476. $errorpart = (is_null($errorpart)) ? '' : self::flattenSingleValue($errorpart);
  477. return self::STATEMENT_IF(self::IS_ERROR($testValue), $errorpart, $testValue);
  478. } // function STATEMENT_IFERROR()
  479. /**
  480. * ATAN2
  481. *
  482. * This function calculates the arc tangent of the two variables x and y. It is similar to
  483. * calculating the arc tangent of y ÷ x, except that the signs of both arguments are used
  484. * to determine the quadrant of the result.
  485. * The arctangent is the angle from the x-axis to a line containing the origin (0, 0) and a
  486. * point with coordinates (xCoordinate, yCoordinate). The angle is given in radians between
  487. * -pi and pi, excluding -pi.
  488. *
  489. * Note that the Excel ATAN2() function accepts its arguments in the reverse order to the standard
  490. * PHP atan2() function, so we need to reverse them here before calling the PHP atan() function.
  491. *
  492. * Excel Function:
  493. * ATAN2(xCoordinate,yCoordinate)
  494. *
  495. * @access public
  496. * @category Mathematical and Trigonometric Functions
  497. * @param float $xCoordinate The x-coordinate of the point.
  498. * @param float $yCoordinate The y-coordinate of the point.
  499. * @return float The inverse tangent of the specified x- and y-coordinates.
  500. */
  501. public static function REVERSE_ATAN2($xCoordinate, $yCoordinate) {
  502. $xCoordinate = (float) self::flattenSingleValue($xCoordinate);
  503. $yCoordinate = (float) self::flattenSingleValue($yCoordinate);
  504. if (($xCoordinate == 0) && ($yCoordinate == 0)) {
  505. return self::$_errorCodes['divisionbyzero'];
  506. }
  507. return atan2($yCoordinate, $xCoordinate);
  508. } // function REVERSE_ATAN2()
  509. /**
  510. * LOG_BASE
  511. *
  512. * Returns the logarithm of a number to a specified base. The default base is 10.
  513. *
  514. * Excel Function:
  515. * LOG(number[,base])
  516. *
  517. * @access public
  518. * @category Mathematical and Trigonometric Functions
  519. * @param float $value The positive real number for which you want the logarithm
  520. * @param float $base The base of the logarithm. If base is omitted, it is assumed to be 10.
  521. * @return float
  522. */
  523. public static function LOG_BASE($number, $base=10) {
  524. $number = self::flattenSingleValue($number);
  525. $base = (is_null($base)) ? 10 : (float) self::flattenSingleValue($base);
  526. return log($number, $base);
  527. } // function LOG_BASE()
  528. /**
  529. * SUM
  530. *
  531. * SUM computes the sum of all the values and cells referenced in the argument list.
  532. *
  533. * Excel Function:
  534. * SUM(value1[,value2[, ...]])
  535. *
  536. * @access public
  537. * @category Mathematical and Trigonometric Functions
  538. * @param mixed $arg,... Data values
  539. * @return float
  540. */
  541. public static function SUM() {
  542. // Return value
  543. $returnValue = 0;
  544. // Loop through the arguments
  545. $aArgs = self::flattenArray(func_get_args());
  546. foreach ($aArgs as $arg) {
  547. // Is it a numeric value?
  548. if ((is_numeric($arg)) && (!is_string($arg))) {
  549. $returnValue += $arg;
  550. }
  551. }
  552. // Return
  553. return $returnValue;
  554. } // function SUM()
  555. /**
  556. * SUMSQ
  557. *
  558. * SUMSQ returns the sum of the squares of the arguments
  559. *
  560. * Excel Function:
  561. * SUMSQ(value1[,value2[, ...]])
  562. *
  563. * @access public
  564. * @category Mathematical and Trigonometric Functions
  565. * @param mixed $arg,... Data values
  566. * @return float
  567. */
  568. public static function SUMSQ() {
  569. // Return value
  570. $returnValue = 0;
  571. // Loop through arguments
  572. $aArgs = self::flattenArray(func_get_args());
  573. foreach ($aArgs as $arg) {
  574. // Is it a numeric value?
  575. if ((is_numeric($arg)) && (!is_string($arg))) {
  576. $returnValue += ($arg * $arg);
  577. }
  578. }
  579. // Return
  580. return $returnValue;
  581. } // function SUMSQ()
  582. /**
  583. * PRODUCT
  584. *
  585. * PRODUCT returns the product of all the values and cells referenced in the argument list.
  586. *
  587. * Excel Function:
  588. * PRODUCT(value1[,value2[, ...]])
  589. *
  590. * @access public
  591. * @category Mathematical and Trigonometric Functions
  592. * @param mixed $arg,... Data values
  593. * @return float
  594. */
  595. public static function PRODUCT() {
  596. // Return value
  597. $returnValue = null;
  598. // Loop through arguments
  599. $aArgs = self::flattenArray(func_get_args());
  600. foreach ($aArgs as $arg) {
  601. // Is it a numeric value?
  602. if ((is_numeric($arg)) && (!is_string($arg))) {
  603. if (is_null($returnValue)) {
  604. $returnValue = $arg;
  605. } else {
  606. $returnValue *= $arg;
  607. }
  608. }
  609. }
  610. // Return
  611. if (is_null($returnValue)) {
  612. return 0;
  613. }
  614. return $returnValue;
  615. } // function PRODUCT()
  616. /**
  617. * QUOTIENT
  618. *
  619. * QUOTIENT function returns the integer portion of a division. Numerator is the divided number
  620. * and denominator is the divisor.
  621. *
  622. * Excel Function:
  623. * QUOTIENT(value1[,value2[, ...]])
  624. *
  625. * @access public
  626. * @category Mathematical and Trigonometric Functions
  627. * @param mixed $arg,... Data values
  628. * @return float
  629. */
  630. public static function QUOTIENT() {
  631. // Return value
  632. $returnValue = null;
  633. // Loop through arguments
  634. $aArgs = self::flattenArray(func_get_args());
  635. foreach ($aArgs as $arg) {
  636. // Is it a numeric value?
  637. if ((is_numeric($arg)) && (!is_string($arg))) {
  638. if (is_null($returnValue)) {
  639. $returnValue = ($arg == 0) ? 0 : $arg;
  640. } else {
  641. if (($returnValue == 0) || ($arg == 0)) {
  642. $returnValue = 0;
  643. } else {
  644. $returnValue /= $arg;
  645. }
  646. }
  647. }
  648. }
  649. // Return
  650. return intval($returnValue);
  651. } // function QUOTIENT()
  652. /**
  653. * MIN
  654. *
  655. * MIN returns the value of the element of the values passed that has the smallest value,
  656. * with negative numbers considered smaller than positive numbers.
  657. *
  658. * Excel Function:
  659. * MIN(value1[,value2[, ...]])
  660. *
  661. * @access public
  662. * @category Statistical Functions
  663. * @param mixed $arg,... Data values
  664. * @return float
  665. */
  666. public static function MIN() {
  667. // Return value
  668. $returnValue = null;
  669. // Loop through arguments
  670. $aArgs = self::flattenArray(func_get_args());
  671. foreach ($aArgs as $arg) {
  672. // Is it a numeric value?
  673. if ((is_numeric($arg)) && (!is_string($arg))) {
  674. if ((is_null($returnValue)) || ($arg < $returnValue)) {
  675. $returnValue = $arg;
  676. }
  677. }
  678. }
  679. // Return
  680. if(is_null($returnValue)) {
  681. return 0;
  682. }
  683. return $returnValue;
  684. } // function MIN()
  685. /**
  686. * MINA
  687. *
  688. * Returns the smallest value in a list of arguments, including numbers, text, and logical values
  689. *
  690. * Excel Function:
  691. * MINA(value1[,value2[, ...]])
  692. *
  693. * @access public
  694. * @category Statistical Functions
  695. * @param mixed $arg,... Data values
  696. * @return float
  697. */
  698. public static function MINA() {
  699. // Return value
  700. $returnValue = null;
  701. // Loop through arguments
  702. $aArgs = self::flattenArray(func_get_args());
  703. foreach ($aArgs as $arg) {
  704. // Is it a numeric value?
  705. if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
  706. if (is_bool($arg)) {
  707. $arg = (integer) $arg;
  708. } elseif (is_string($arg)) {
  709. $arg = 0;
  710. }
  711. if ((is_null($returnValue)) || ($arg < $returnValue)) {
  712. $returnValue = $arg;
  713. }
  714. }
  715. }
  716. // Return
  717. if(is_null($returnValue)) {
  718. return 0;
  719. }
  720. return $returnValue;
  721. } // function MINA()
  722. /**
  723. * SMALL
  724. *
  725. * Returns the nth smallest value in a data set. You can use this function to
  726. * select a value based on its relative standing.
  727. *
  728. * Excel Function:
  729. * SMALL(value1[,value2[, ...]],entry)
  730. *
  731. * @access public
  732. * @category Statistical Functions
  733. * @param mixed $arg,... Data values
  734. * @param int $entry Position (ordered from the smallest) in the array or range of data to return
  735. * @return float
  736. */
  737. public static function SMALL() {
  738. $aArgs = self::flattenArray(func_get_args());
  739. // Calculate
  740. $entry = array_pop($aArgs);
  741. if ((is_numeric($entry)) && (!is_string($entry))) {
  742. $mArgs = array();
  743. foreach ($aArgs as $arg) {
  744. // Is it a numeric value?
  745. if ((is_numeric($arg)) && (!is_string($arg))) {
  746. $mArgs[] = $arg;
  747. }
  748. }
  749. $count = self::COUNT($mArgs);
  750. $entry = floor(--$entry);
  751. if (($entry < 0) || ($entry >= $count) || ($count == 0)) {
  752. return self::$_errorCodes['num'];
  753. }
  754. sort($mArgs);
  755. return $mArgs[$entry];
  756. }
  757. return self::$_errorCodes['value'];
  758. } // function SMALL()
  759. /**
  760. * MAX
  761. *
  762. * MAX returns the value of the element of the values passed that has the highest value,
  763. * with negative numbers considered smaller than positive numbers.
  764. *
  765. * Excel Function:
  766. * MAX(value1[,value2[, ...]])
  767. *
  768. * @access public
  769. * @category Statistical Functions
  770. * @param mixed $arg,... Data values
  771. * @return float
  772. */
  773. public static function MAX() {
  774. // Return value
  775. $returnValue = null;
  776. // Loop through arguments
  777. $aArgs = self::flattenArray(func_get_args());
  778. foreach ($aArgs as $arg) {
  779. // Is it a numeric value?
  780. if ((is_numeric($arg)) && (!is_string($arg))) {
  781. if ((is_null($returnValue)) || ($arg > $returnValue)) {
  782. $returnValue = $arg;
  783. }
  784. }
  785. }
  786. // Return
  787. if(is_null($returnValue)) {
  788. return 0;
  789. }
  790. return $returnValue;
  791. } // function MAX()
  792. /**
  793. * MAXA
  794. *
  795. * Returns the greatest value in a list of arguments, including numbers, text, and logical values
  796. *
  797. * Excel Function:
  798. * MAXA(value1[,value2[, ...]])
  799. *
  800. * @access public
  801. * @category Statistical Functions
  802. * @param mixed $arg,... Data values
  803. * @return float
  804. */
  805. public static function MAXA() {
  806. // Return value
  807. $returnValue = null;
  808. // Loop through arguments
  809. $aArgs = self::flattenArray(func_get_args());
  810. foreach ($aArgs as $arg) {
  811. // Is it a numeric value?
  812. if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
  813. if (is_bool($arg)) {
  814. $arg = (integer) $arg;
  815. } elseif (is_string($arg)) {
  816. $arg = 0;
  817. }
  818. if ((is_null($returnValue)) || ($arg > $returnValue)) {
  819. $returnValue = $arg;
  820. }
  821. }
  822. }
  823. // Return
  824. if(is_null($returnValue)) {
  825. return 0;
  826. }
  827. return $returnValue;
  828. } // function MAXA()
  829. /**
  830. * LARGE
  831. *
  832. * Returns the nth largest value in a data set. You can use this function to
  833. * select a value based on its relative standing.
  834. *
  835. * Excel Function:
  836. * LARGE(value1[,value2[, ...]],entry)
  837. *
  838. * @access public
  839. * @category Statistical Functions
  840. * @param mixed $arg,... Data values
  841. * @param int $entry Position (ordered from the largest) in the array or range of data to return
  842. * @return float
  843. *
  844. */
  845. public static function LARGE() {
  846. $aArgs = self::flattenArray(func_get_args());
  847. // Calculate
  848. $entry = floor(array_pop($aArgs));
  849. if ((is_numeric($entry)) && (!is_string($entry))) {
  850. $mArgs = array();
  851. foreach ($aArgs as $arg) {
  852. // Is it a numeric value?
  853. if ((is_numeric($arg)) && (!is_string($arg))) {
  854. $mArgs[] = $arg;
  855. }
  856. }
  857. $count = self::COUNT($mArgs);
  858. $entry = floor(--$entry);
  859. if (($entry < 0) || ($entry >= $count) || ($count == 0)) {
  860. return self::$_errorCodes['num'];
  861. }
  862. rsort($mArgs);
  863. return $mArgs[$entry];
  864. }
  865. return self::$_errorCodes['value'];
  866. } // function LARGE()
  867. /**
  868. * PERCENTILE
  869. *
  870. * Returns the nth percentile of values in a range..
  871. *
  872. * Excel Function:
  873. * PERCENTILE(value1[,value2[, ...]],entry)
  874. *
  875. * @access public
  876. * @category Statistical Functions
  877. * @param mixed $arg,... Data values
  878. * @param float $entry Percentile value in the range 0..1, inclusive.
  879. * @return float
  880. */
  881. public static function PERCENTILE() {
  882. $aArgs = self::flattenArray(func_get_args());
  883. // Calculate
  884. $entry = array_pop($aArgs);
  885. if ((is_numeric($entry)) && (!is_string($entry))) {
  886. if (($entry < 0) || ($entry > 1)) {
  887. return self::$_errorCodes['num'];
  888. }
  889. $mArgs = array();
  890. foreach ($aArgs as $arg) {
  891. // Is it a numeric value?
  892. if ((is_numeric($arg)) && (!is_string($arg))) {
  893. $mArgs[] = $arg;
  894. }
  895. }
  896. $mValueCount = count($mArgs);
  897. if ($mValueCount > 0) {
  898. sort($mArgs);
  899. $count = self::COUNT($mArgs);
  900. $index = $entry * ($count-1);
  901. $iBase = floor($index);
  902. if ($index == $iBase) {
  903. return $mArgs[$index];
  904. } else {
  905. $iNext = $iBase + 1;
  906. $iProportion = $index - $iBase;
  907. return $mArgs[$iBase] + (($mArgs[$iNext] - $mArgs[$iBase]) * $iProportion) ;
  908. }
  909. }
  910. }
  911. return self::$_errorCodes['value'];
  912. } // function PERCENTILE()
  913. /**
  914. * QUARTILE
  915. *
  916. * Returns the quartile of a data set.
  917. *
  918. * Excel Function:
  919. * QUARTILE(value1[,value2[, ...]],entry)
  920. *
  921. * @access public
  922. * @category Statistical Functions
  923. * @param mixed $arg,... Data values
  924. * @param int $entry Quartile value in the range 1..3, inclusive.
  925. * @return float
  926. */
  927. public static function QUARTILE() {
  928. $aArgs = self::flattenArray(func_get_args());
  929. // Calculate
  930. $entry = floor(array_pop($aArgs));
  931. if ((is_numeric($entry)) && (!is_string($entry))) {
  932. $entry /= 4;
  933. if (($entry < 0) || ($entry > 1)) {
  934. return self::$_errorCodes['num'];
  935. }
  936. return self::PERCENTILE($aArgs,$entry);
  937. }
  938. return self::$_errorCodes['value'];
  939. } // function QUARTILE()
  940. /**
  941. * COUNT
  942. *
  943. * Counts the number of cells that contain numbers within the list of arguments
  944. *
  945. * Excel Function:
  946. * COUNT(value1[,value2[, ...]])
  947. *
  948. * @access public
  949. * @category Statistical Functions
  950. * @param mixed $arg,... Data values
  951. * @return int
  952. */
  953. public static function COUNT() {
  954. // Return value
  955. $returnValue = 0;
  956. // Loop through arguments
  957. $aArgs = self::flattenArrayIndexed(func_get_args());
  958. foreach ($aArgs as $k => $arg) {
  959. if ((is_bool($arg)) &&
  960. ((!self::isCellValue($k)) || (self::$compatibilityMode == self::COMPATIBILITY_OPENOFFICE))) {
  961. $arg = (integer) $arg;
  962. }
  963. // Is it a numeric value?
  964. if ((is_numeric($arg)) && (!is_string($arg))) {
  965. ++$returnValue;
  966. }
  967. }
  968. // Return
  969. return $returnValue;
  970. } // function COUNT()
  971. /**
  972. * COUNTBLANK
  973. *
  974. * Counts the number of empty cells within the list of arguments
  975. *
  976. * Excel Function:
  977. * COUNTBLANK(value1[,value2[, ...]])
  978. *
  979. * @access public
  980. * @category Statistical Functions
  981. * @param mixed $arg,... Data values
  982. * @return int
  983. */
  984. public static function COUNTBLANK() {
  985. // Return value
  986. $returnValue = 0;
  987. // Loop through arguments
  988. $aArgs = self::flattenArray(func_get_args());
  989. foreach ($aArgs as $arg) {
  990. // Is it a blank cell?
  991. if ((is_null($arg)) || ((is_string($arg)) && ($arg == ''))) {
  992. ++$returnValue;
  993. }
  994. }
  995. // Return
  996. return $returnValue;
  997. } // function COUNTBLANK()
  998. /**
  999. * COUNTA
  1000. *
  1001. * Counts the number of cells that are not empty within the list of arguments
  1002. *
  1003. * Excel Function:
  1004. * COUNTA(value1[,value2[, ...]])
  1005. *
  1006. * @access public
  1007. * @category Statistical Functions
  1008. * @param mixed $arg,... Data values
  1009. * @return int
  1010. */
  1011. public static function COUNTA() {
  1012. // Return value
  1013. $returnValue = 0;
  1014. // Loop through arguments
  1015. $aArgs = self::flattenArray(func_get_args());
  1016. foreach ($aArgs as $arg) {
  1017. // Is it a numeric, boolean or string value?
  1018. if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
  1019. ++$returnValue;
  1020. }
  1021. }
  1022. // Return
  1023. return $returnValue;
  1024. } // function COUNTA()
  1025. /**
  1026. * COUNTIF
  1027. *
  1028. * Counts the number of cells that contain numbers within the list of arguments
  1029. *
  1030. * Excel Function:
  1031. * COUNTIF(value1[,value2[, ...]],condition)
  1032. *
  1033. * @access public
  1034. * @category Statistical Functions
  1035. * @param mixed $arg,... Data values
  1036. * @param string $condition The criteria that defines which cells will be counted.
  1037. * @return int
  1038. */
  1039. public static function COUNTIF($aArgs,$condition) {
  1040. // Return value
  1041. $returnValue = 0;
  1042. $aArgs = self::flattenArray($aArgs);
  1043. $condition = self::flattenSingleValue($condition);
  1044. if (!in_array($condition{0},array('>', '<', '='))) {
  1045. if (!is_numeric($condition)) { $condition = PHPExcel_Calculation::_wrapResult(strtoupper($condition)); }
  1046. $condition = '='.$condition;
  1047. } else {
  1048. preg_match('/([<>=]+)(.*)/',$condition,$matches);
  1049. list(,$operator,$operand) = $matches;
  1050. if (!is_numeric($operand)) { $operand = PHPExcel_Calculation::_wrapResult(strtoupper($operand)); }
  1051. $condition = $operator.$operand;
  1052. }
  1053. // Loop through arguments
  1054. foreach ($aArgs as $arg) {
  1055. if (!is_numeric($arg)) { $arg = PHPExcel_Calculation::_wrapResult(strtoupper($arg)); }
  1056. $testCondition = '='.$arg.$condition;
  1057. if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
  1058. // Is it a value within our criteria
  1059. ++$returnValue;
  1060. }
  1061. }
  1062. // Return
  1063. return $returnValue;
  1064. } // function COUNTIF()
  1065. /**
  1066. * SUMIF
  1067. *
  1068. * Counts the number of cells that contain numbers within the list of arguments
  1069. *
  1070. * Excel Function:
  1071. * SUMIF(value1[,value2[, ...]],condition)
  1072. *
  1073. * @access public
  1074. * @category Mathematical and Trigonometric Functions
  1075. * @param mixed $arg,... Data values
  1076. * @param string $condition The criteria that defines which cells will be summed.
  1077. * @return float
  1078. */
  1079. public static function SUMIF($aArgs,$condition,$sumArgs = array()) {
  1080. // Return value
  1081. $returnValue = 0;
  1082. $aArgs = self::flattenArray($aArgs);
  1083. $sumArgs = self::flattenArray($sumArgs);
  1084. if (count($sumArgs) == 0) {
  1085. $sumArgs = $aArgs;
  1086. }
  1087. if (!in_array($condition{0},array('>', '<', '='))) {
  1088. if (!is_numeric($condition)) { $condition = PHPExcel_Calculation::_wrapResult(strtoupper($condition)); }
  1089. $condition = '='.$condition;
  1090. } else {
  1091. preg_match('/([<>=]+)(.*)/',$condition,$matches);
  1092. list(,$operator,$operand) = $matches;
  1093. if (!is_numeric($operand)) { $operand = PHPExcel_Calculation::_wrapResult(strtoupper($operand)); }
  1094. $condition = $operator.$operand;
  1095. }
  1096. // Loop through arguments
  1097. foreach ($aArgs as $key => $arg) {
  1098. if (!is_numeric($arg)) { $arg = PHPExcel_Calculation::_wrapResult(strtoupper($arg)); }
  1099. $testCondition = '='.$arg.$condition;
  1100. if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
  1101. // Is it a value within our criteria
  1102. $returnValue += $sumArgs[$key];
  1103. }
  1104. }
  1105. // Return
  1106. return $returnValue;
  1107. } // function SUMIF()
  1108. /**
  1109. * AVERAGE
  1110. *
  1111. * Returns the average (arithmetic mean) of the arguments
  1112. *
  1113. * Excel Function:
  1114. * AVERAGE(value1[,value2[, ...]])
  1115. *
  1116. * @access public
  1117. * @category Statistical Functions
  1118. * @param mixed $arg,... Data values
  1119. * @return float
  1120. */
  1121. public static function AVERAGE() {
  1122. $aArgs = self::flattenArrayIndexed(func_get_args());
  1123. $returnValue = $aCount = 0;
  1124. // Loop through arguments
  1125. foreach ($aArgs as $k => $arg) {
  1126. if ((is_bool($arg)) &&
  1127. ((!self::isCellValue($k)) || (self::$compatibilityMode == self::COMPATIBILITY_OPENOFFICE))) {
  1128. $arg = (integer) $arg;
  1129. }
  1130. // Is it a numeric value?
  1131. if ((is_numeric($arg)) && (!is_string($arg))) {
  1132. if (is_null($returnValue)) {
  1133. $returnValue = $arg;
  1134. } else {
  1135. $returnValue += $arg;
  1136. }
  1137. ++$aCount;
  1138. }
  1139. }
  1140. // Return
  1141. if ($aCount > 0) {
  1142. return $returnValue / $aCount;
  1143. } else {
  1144. return self::$_errorCodes['divisionbyzero'];
  1145. }
  1146. } // function AVERAGE()
  1147. /**
  1148. * AVERAGEA
  1149. *
  1150. * Returns the average of its arguments, including numbers, text, and logical values
  1151. *
  1152. * Excel Function:
  1153. * AVERAGEA(value1[,value2[, ...]])
  1154. *
  1155. * @access public
  1156. * @category Statistical Functions
  1157. * @param mixed $arg,... Data values
  1158. * @return float
  1159. */
  1160. public static function AVERAGEA() {
  1161. // Return value
  1162. $returnValue = null;
  1163. // Loop through arguments
  1164. $aArgs = self::flattenArrayIndexed(func_get_args());
  1165. $aCount = 0;
  1166. foreach ($aArgs as $k => $arg) {
  1167. if ((is_bool($arg)) &&
  1168. (!self::isMatrixValue($k))) {
  1169. } else {
  1170. if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
  1171. if (is_bool($arg)) {
  1172. $arg = (integer) $arg;
  1173. } elseif (is_string($arg)) {
  1174. $arg = 0;
  1175. }
  1176. if (is_null($returnValue)) {
  1177. $returnValue = $arg;
  1178. } else {
  1179. $returnValue += $arg;
  1180. }
  1181. ++$aCount;
  1182. }
  1183. }
  1184. }
  1185. // Return
  1186. if ($aCount > 0) {
  1187. return $returnValue / $aCount;
  1188. } else {
  1189. return self::$_errorCodes['divisionbyzero'];
  1190. }
  1191. } // function AVERAGEA()
  1192. /**
  1193. * MEDIAN
  1194. *
  1195. * Returns the median of the given numbers. The median is the number in the middle of a set of numbers.
  1196. *
  1197. * Excel Function:
  1198. * MEDIAN(value1[,value2[, ...]])
  1199. *
  1200. * @access public
  1201. * @category Statistical Functions
  1202. * @param mixed $arg,... Data values
  1203. * @return float
  1204. */
  1205. public static function MEDIAN() {
  1206. // Return value
  1207. $returnValue = self::$_errorCodes['num'];
  1208. $mArgs = array();
  1209. // Loop through arguments
  1210. $aArgs = self::flattenArray(func_get_args());
  1211. foreach ($aArgs as $arg) {
  1212. // Is it a numeric value?
  1213. if ((is_numeric($arg)) && (!is_string($arg))) {
  1214. $mArgs[] = $arg;
  1215. }
  1216. }
  1217. $mValueCount = count($mArgs);
  1218. if ($mValueCount > 0) {
  1219. sort($mArgs,SORT_NUMERIC);
  1220. $mValueCount = $mValueCount / 2;
  1221. if ($mValueCount == floor($mValueCount)) {
  1222. $returnValue = ($mArgs[$mValueCount--] + $mArgs[$mValueCount]) / 2;
  1223. } else {
  1224. $mValueCount == floor($mValueCount);
  1225. $returnValue = $mArgs[$mValueCount];
  1226. }
  1227. }
  1228. // Return
  1229. return $returnValue;
  1230. } // function MEDIAN()
  1231. //
  1232. // Special variant of array_count_values that isn't limited to strings and integers,
  1233. // but can work with floating point numbers as values
  1234. //
  1235. private static function _modeCalc($data) {
  1236. $frequencyArray = array();
  1237. foreach($data as $datum) {
  1238. $found = False;
  1239. foreach($frequencyArray as $key => $value) {
  1240. if ((string) $value['value'] == (string) $datum) {
  1241. ++$frequencyArray[$key]['frequency'];
  1242. $found = True;
  1243. break;
  1244. }
  1245. }
  1246. if (!$found) {
  1247. $frequencyArray[] = array('value' => $datum,
  1248. 'frequency' => 1 );
  1249. }
  1250. }
  1251. foreach($frequencyArray as $key => $value) {
  1252. $frequencyList[$key] = $value['frequency'];
  1253. $valueList[$key] = $value['value'];
  1254. }
  1255. array_multisort($frequencyList, SORT_DESC, $valueList, SORT_ASC, SORT_NUMERIC, $frequencyArray);
  1256. if ($frequencyArray[0]['frequency'] == 1) {
  1257. return self::NA();
  1258. }
  1259. return $frequencyArray[0]['value'];
  1260. } // function _modeCalc()
  1261. /**
  1262. * MODE
  1263. *
  1264. * Returns the most frequently occurring, or repetitive, value in an array or range of data
  1265. *
  1266. * Excel Function:
  1267. * MODE(value1[,value2[, ...]])
  1268. *
  1269. * @access public
  1270. * @category Statistical Functions
  1271. * @param mixed $arg,... Data values
  1272. * @return float
  1273. */
  1274. public static function MODE() {
  1275. // Return value
  1276. $returnValue = self::NA();
  1277. // Loop through arguments
  1278. $aArgs = self::flattenArray(func_get_args());
  1279. $mArgs = array();
  1280. foreach ($aArgs as $arg) {
  1281. // Is it a numeric value?
  1282. if ((is_numeric($arg)) && (!is_string($arg))) {
  1283. $mArgs[] = $arg;
  1284. }
  1285. }
  1286. if (count($mArgs) > 0) {
  1287. return self::_modeCalc($mArgs);
  1288. }
  1289. // Return
  1290. return $returnValue;
  1291. } // function MODE()
  1292. /**
  1293. * DEVSQ
  1294. *
  1295. * Returns the sum of squares of deviations of data points from their sample mean.
  1296. *
  1297. * Excel Function:
  1298. * DEVSQ(value1[,value2[, ...]])
  1299. *
  1300. * @access public
  1301. * @category Statistical Functions
  1302. * @param mixed $arg,... Data values
  1303. * @return float
  1304. */
  1305. public static function DEVSQ() {
  1306. $aArgs = self::flattenArrayIndexed(func_get_args());
  1307. // Return value
  1308. $returnValue = null;
  1309. $aMean = self::AVERAGE($aArgs);
  1310. if ($aMean != self::$_errorCodes['divisionbyzero']) {
  1311. $aCount = -1;
  1312. foreach ($aArgs as $k => $arg) {
  1313. // Is it a numeric value?
  1314. if ((is_bool($arg)) &&
  1315. ((!self::isCellValue($k)) || (self::$compatibilityMode == self::COMPATIBILITY_OPENOFFICE))) {
  1316. $arg = (integer) $arg;
  1317. }
  1318. if ((is_numeric($arg)) && (!is_string($arg))) {
  1319. if (is_null($returnValue)) {
  1320. $returnValue = pow(($arg - $aMean),2);
  1321. } else {
  1322. $returnValue += pow(($arg - $aMean),2);
  1323. }
  1324. ++$aCount;
  1325. }
  1326. }
  1327. // Return
  1328. if (is_null($returnValue)) {
  1329. return self::$_errorCodes['num'];
  1330. } else {
  1331. return $returnValue;
  1332. }
  1333. }
  1334. return self::NA();
  1335. } // function DEVSQ()
  1336. /**
  1337. * AVEDEV
  1338. *
  1339. * Returns the average of the absolute deviations of data points from their mean.
  1340. * AVEDEV is a measure of the variability in a data set.
  1341. *
  1342. * Excel Function:
  1343. * AVEDEV(value1[,value2[, ...]])
  1344. *
  1345. * @access public
  1346. * @category Statistical Functions
  1347. * @param mixed $arg,... Data values
  1348. * @return float
  1349. */
  1350. public static function AVEDEV() {
  1351. $aArgs = self::flattenArrayIndexed(func_get_args());
  1352. // Return value
  1353. $returnValue = null;
  1354. $aMean = self::AVERAGE($aArgs);
  1355. if ($aMean != self::$_errorCodes['divisionbyzero']) {
  1356. $aCount = 0;
  1357. foreach ($aArgs as $k => $arg) {
  1358. if ((is_bool($arg)) &&
  1359. ((!self::isCellValue($k)) || (self::$compatibilityMode == self::COMPATIBILITY_OPENOFFICE))) {
  1360. $arg = (integer) $arg;
  1361. }
  1362. // Is it a numeric value?
  1363. if ((is_numeric($arg)) && (!is_string($arg))) {
  1364. if (is_null($returnValue)) {
  1365. $returnValue = abs($arg - $aMean);
  1366. } else {
  1367. $returnValue += abs($arg - $aMean);
  1368. }
  1369. ++$aCount;
  1370. }
  1371. }
  1372. // Return
  1373. if ($aCount == 0) {
  1374. return self::$_errorCodes['divisionbyzero'];
  1375. }
  1376. return $returnValue / $aCount;
  1377. }
  1378. return self::$_errorCodes['num'];
  1379. } // function AVEDEV()
  1380. /**
  1381. * GEOMEAN
  1382. *
  1383. * Returns the geometric mean of an array or range of positive data. For example, you
  1384. * can use GEOMEAN to calculate average growth rate given compound interest with
  1385. * variable rates.
  1386. *
  1387. * Excel Function:
  1388. * GEOMEAN(value1[,value2[, ...]])
  1389. *
  1390. * @access public
  1391. * @category Statistical Functions
  1392. * @param mixed $arg,... Data values
  1393. * @return float
  1394. */
  1395. public static function GEOMEAN() {
  1396. $aArgs = self::flattenArray(func_get_args());
  1397. $aMean = self::PRODUCT($aArgs);
  1398. if (is_numeric($aMean) && ($aMean > 0)) {
  1399. $aCount = self::COUNT($aArgs) ;
  1400. if (self::MIN($aArgs) > 0) {
  1401. return pow($aMean, (1 / $aCount));
  1402. }
  1403. }
  1404. return self::$_errorCodes['num'];
  1405. } // GEOMEAN()
  1406. /**
  1407. * HARMEAN
  1408. *
  1409. * Returns the harmonic mean of a data set. The harmonic mean is the reciprocal of the
  1410. * arithmetic mean of reciprocals.
  1411. *
  1412. * Excel Function:
  1413. * HARMEAN(value1[,value2[, ...]])
  1414. *
  1415. * @access public
  1416. * @category Statistical Functions
  1417. * @param mixed $arg,... Data values
  1418. * @return float
  1419. */
  1420. public static function HARMEAN() {
  1421. // Return value
  1422. $returnValue = self::NA();
  1423. // Loop through arguments
  1424. $aArgs = self::flattenArray(func_get_args());
  1425. if (self::MIN($aArgs) < 0) {
  1426. return self::$_errorCodes['num'];
  1427. }
  1428. $aCount = 0;
  1429. foreach ($aArgs as $arg) {
  1430. // Is it a numeric value?
  1431. if ((is_numeric($arg)) && (!is_string($arg))) {
  1432. if ($arg <= 0) {
  1433. return self::$_errorCodes['num'];
  1434. }
  1435. if (is_null($returnValue)) {
  1436. $returnValue = (1 / $arg);
  1437. } else {
  1438. $returnValue += (1 / $arg);
  1439. }
  1440. ++$aCount;
  1441. }
  1442. }
  1443. // Return
  1444. if ($aCount > 0) {
  1445. return 1 / ($returnValue / $aCount);
  1446. } else {
  1447. return $returnValue;
  1448. }
  1449. } // function HARMEAN()
  1450. /**
  1451. * TRIMMEAN
  1452. *
  1453. * Returns the mean of the interior of a data set. TRIMMEAN calculates the mean
  1454. * taken by excluding a percentage of data points from the top and bottom tails
  1455. * of a data set.
  1456. *
  1457. * Excel Function:
  1458. * TRIMEAN(value1[,value2[, ...]],$discard)
  1459. *
  1460. * @access public
  1461. * @category Statistical Functions
  1462. * @param mixed $arg,... Data values
  1463. * @param float $discard Percentage to discard
  1464. * @return float
  1465. */
  1466. public static function TRIMMEAN() {
  1467. $aArgs = self::flattenArray(func_get_args());
  1468. // Calculate
  1469. $percent = array_pop($aArgs);
  1470. if ((is_numeric($percent)) && (!is_string($percent))) {
  1471. if (($percent < 0) || ($percent > 1)) {
  1472. return self::$_errorCodes['num'];
  1473. }
  1474. $mArgs = array();
  1475. foreach ($aArgs as $arg) {
  1476. // Is it a numeric value?
  1477. if ((is_numeric($arg)) && (!is_string($arg))) {
  1478. $mArgs[] = $arg;
  1479. }
  1480. }
  1481. $discard = floor(self::COUNT($mArgs) * $percent / 2);
  1482. sort($mArgs);
  1483. for ($i=0; $i < $discard; ++$i) {
  1484. array_pop($mArgs);
  1485. array_shift($mArgs);
  1486. }
  1487. return self::AVERAGE($mArgs);
  1488. }
  1489. return self::$_errorCodes['value'];
  1490. } // function TRIMMEAN()
  1491. /**
  1492. * STDEV
  1493. *
  1494. * Estimates standard deviation based on a sample. The standard deviation is a measure of how
  1495. * widely values are dispersed from the average value (the mean).
  1496. *
  1497. * Excel Function:
  1498. * STDEV(value1[,value2[, ...]])
  1499. *
  1500. * @access public
  1501. * @category Statistical Functions
  1502. * @param mixed $arg,... Data values
  1503. * @return float
  1504. */
  1505. public static function STDEV() {
  1506. $aArgs = self::flattenArrayIndexed(func_get_args());
  1507. // Return value
  1508. $returnValue = null;
  1509. $aMean = self::AVERAGE($aArgs);
  1510. if (!is_null($aMean)) {
  1511. $aCount = -1;
  1512. foreach ($aArgs as $k => $arg) {
  1513. if ((is_bool($arg)) &&
  1514. ((!self::isCellValue($k)) || (self::$compatibilityMode == self::COMPATIBILITY_OPENOFFICE))) {
  1515. $arg = (integer) $arg;
  1516. }
  1517. // Is it a numeric value?
  1518. if ((is_numeric($arg)) && (!is_string($arg))) {
  1519. if (is_null($returnValue)) {
  1520. $returnValue = pow(($arg - $aMean),2);
  1521. } else {
  1522. $returnValue += pow(($arg - $aMean),2);
  1523. }
  1524. ++$aCount;
  1525. }
  1526. }
  1527. // Return
  1528. if (($aCount > 0) && ($returnValue > 0)) {
  1529. return sqrt($returnValue / $aCount);
  1530. }
  1531. }
  1532. return self::$_errorCodes['divisionbyzero'];
  1533. } // function STDEV()
  1534. /**
  1535. * STDEVA
  1536. *
  1537. * Estimates standard deviation based on a sample, including numbers, text, and logical values
  1538. *
  1539. * Excel Function:
  1540. * STDEVA(value1[,value2[, ...]])
  1541. *
  1542. * @access public
  1543. * @category Statistical Functions
  1544. * @param mixed $arg,... Data values
  1545. * @return float
  1546. */
  1547. public static function STDEVA() {
  1548. $aArgs = self::flattenArrayIndexed(func_get_args());
  1549. // Return value
  1550. $returnValue = null;
  1551. $aMean = self::AVERAGEA($aArgs);
  1552. if (!is_null($aMean)) {
  1553. $aCount = -1;
  1554. foreach ($aArgs as $k => $arg) {
  1555. if ((is_bool($arg)) &&
  1556. (!self::isMatrixValue($k))) {
  1557. } else {
  1558. // Is it a numeric value?
  1559. if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) {
  1560. if (is_bool($arg)) {
  1561. $arg = (integer) $arg;
  1562. } elseif (is_string($arg)) {
  1563. $arg = 0;
  1564. }
  1565. if (is_null($returnValue)) {
  1566. $returnValue = pow(($arg - $aMean),2);
  1567. } else {
  1568. $returnValue += pow(($arg - $aMean),2);
  1569. }
  1570. ++$aCount;
  1571. }
  1572. }
  1573. }
  1574. // Return
  1575. if (($aCount > 0) && ($returnValue > 0)) {
  1576. return sqrt($returnValue / $aCount);
  1577. }
  1578. }
  1579. return self::$_errorCodes['divisionbyzero'];
  1580. } // function STDEVA()
  1581. /**
  1582. * STDEVP
  1583. *
  1584. * Calculates standard deviation based on the entire population
  1585. *
  1586. * Excel Function:
  1587. * STDEVP(value1[,value2[, ...]])
  1588. *
  1589. * @access public
  1590. * @category Statistical Functions
  1591. * @param mixed $arg,... Data values
  1592. * @return float
  1593. */
  1594. public static function STDEVP() {
  1595. $aArgs = self::flattenArrayIndexed(func_get_args());
  1596. // Return value
  1597. $returnValue = null;
  1598. $aMean = self::AVERAGE($aArgs);
  1599. if (!is_null($aMean)) {
  1600. $aCount = 0;
  1601. foreach ($aArgs as $k => $arg) {
  1602. if ((is_bool($arg)) &&
  1603. ((!self::isCellValue($k)) || (self::$compatibilityMode == self::COMPATIBILITY_OPENOFFICE))) {
  1604. $arg = (integer) $arg;
  1605. }
  1606. // Is it a numeric value?
  1607. if ((is_numeric($arg)) && (!is_string($arg))) {
  1608. if (is_null($returnValue)) {
  1609. $returnValue = pow(($arg - $aMean),2);
  1610. } else {
  1611. $returnValue += pow(($arg - $aMean),2);
  1612. }
  1613. ++$aCount;
  1614. }
  1615. }
  1616. // Return
  1617. if (($aCount > 0) && ($returnValue > 0)) {
  1618. return sqrt($returnValue / $aCount);
  1619. }
  1620. }
  1621. return self::$_errorCodes['divisionbyzero'];
  1622. } // function STDEVP()
  1623. /**
  1624. * STDEVPA
  1625. *
  1626. * Calculates standard deviation based on the entire population, including numbers, text, and logical values
  1627. *
  1628. * Excel Function:
  1629. * STDEVPA(value1[,value2[, ...]])
  1630. *
  1631. * @access public
  1632. * @category Statistical Functions
  1633. * @param mixed $arg,... Data values
  1634. * @return float
  1635. */
  1636. public static function STDEVPA() {
  1637. $aArgs = self::flattenArrayIndexed(func_get_args());
  1638. // Return value
  1639. $returnValue = null;
  1640. $aMean = self::AVERAGEA($aArgs);
  1641. if (!is_null($aMean)) {
  1642. $aCount = 0;
  1643. foreach ($aArgs as $k => $arg) {
  1644. if ((is_bool($arg)) &&
  1645. (!self::isMatrixValue($k))) {
  1646. } else {
  1647. // Is it a numeric value?
  1648. if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) {
  1649. if (is_bool($arg)) {
  1650. $arg = (integer) $arg;
  1651. } elseif (is_string($arg)) {
  1652. $arg = 0;
  1653. }
  1654. if (is_null($returnValue)) {
  1655. $returnValue = pow(($arg - $aMean),2);
  1656. } else {
  1657. $returnValue += pow(($arg - $aMean),2);
  1658. }
  1659. ++$aCount;
  1660. }
  1661. }
  1662. }
  1663. // Return
  1664. if (($aCount > 0) && ($returnValue > 0)) {
  1665. return sqrt($returnValue / $aCount);
  1666. }
  1667. }
  1668. return self::$_errorCodes['divisionbyzero'];
  1669. } // function STDEVPA()
  1670. /**
  1671. * VARFunc
  1672. *
  1673. * Estimates variance based on a sample.
  1674. *
  1675. * Excel Function:
  1676. * VAR(value1[,value2[, ...]])
  1677. *
  1678. * @access public
  1679. * @category Statistical Functions
  1680. * @param mixed $arg,... Data values
  1681. * @return float
  1682. */
  1683. public static function VARFunc() {
  1684. // Return value
  1685. $returnValue = self::$_errorCodes['divisionbyzero'];
  1686. $summerA = $summerB = 0;
  1687. // Loop through arguments
  1688. $aArgs = self::flattenArray(func_get_args());
  1689. $aCount = 0;
  1690. foreach ($aArgs as $arg) {
  1691. if (is_bool($arg)) { $arg = (integer) $arg; }
  1692. // Is it a numeric value?
  1693. if ((is_numeric($arg)) && (!is_string($arg))) {
  1694. $summerA += ($arg * $arg);
  1695. $summerB += $arg;
  1696. ++$aCount;
  1697. }
  1698. }
  1699. // Return
  1700. if ($aCount > 1) {
  1701. $summerA *= $aCount;
  1702. $summerB *= $summerB;
  1703. $returnValue = ($summerA - $summerB) / ($aCount * ($aCount - 1));
  1704. }
  1705. return $returnValue;
  1706. } // function VARFunc()
  1707. /**
  1708. * VARA
  1709. *
  1710. * Estimates variance based on a sample, including numbers, text, and logical values
  1711. *
  1712. * Excel Function:
  1713. * VARA(value1[,value2[, ...]])
  1714. *
  1715. * @access public
  1716. * @category Statistical Functions
  1717. * @param mixed $arg,... Data values
  1718. * @return float
  1719. */
  1720. public static function VARA() {
  1721. // Return value
  1722. $returnValue = self::$_errorCodes['divisionbyzero'];
  1723. $summerA = $summerB = 0;
  1724. // Loop through arguments
  1725. $aArgs = self::flattenArrayIndexed(func_get_args());
  1726. $aCount = 0;
  1727. foreach ($aArgs as $k => $arg) {
  1728. if ((is_string($arg)) &&
  1729. (self::isValue($k))) {
  1730. return self::$_errorCodes['value'];
  1731. } elseif ((is_string($arg)) &&
  1732. (!self::isMatrixValue($k))) {
  1733. } else {
  1734. // Is it a numeric value?
  1735. if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) {
  1736. if (is_bool($arg)) {
  1737. $arg = (integer) $arg;
  1738. } elseif (is_string($arg)) {
  1739. $arg = 0;
  1740. }
  1741. $summerA += ($arg * $arg);
  1742. $summerB += $arg;
  1743. ++$aCount;
  1744. }
  1745. }
  1746. }
  1747. // Return
  1748. if ($aCount > 1) {
  1749. $summerA *= $aCount;
  1750. $summerB *= $summerB;
  1751. $returnValue = ($summerA - $summerB) / ($aCount * ($aCount - 1));
  1752. }
  1753. return $returnValue;
  1754. } // function VARA()
  1755. /**
  1756. * VARP
  1757. *
  1758. * Calculates variance based on the entire population
  1759. *
  1760. * Excel Function:
  1761. * VARP(value1[,value2[, ...]])
  1762. *
  1763. * @access public
  1764. * @category Statistical Functions
  1765. * @param mixed $arg,... Data values
  1766. * @return float
  1767. */
  1768. public static function VARP() {
  1769. // Return value
  1770. $returnValue = self::$_errorCodes['divisionbyzero'];
  1771. $summerA = $summerB = 0;
  1772. // Loop through arguments
  1773. $aArgs = self::flattenArray(func_get_args());
  1774. $aCount = 0;
  1775. foreach ($aArgs as $arg) {
  1776. if (is_bool($arg)) { $arg = (integer) $arg; }
  1777. // Is it a numeric value?
  1778. if ((is_numeric($arg)) && (!is_string($arg))) {
  1779. $summerA += ($arg * $arg);
  1780. $summerB += $arg;
  1781. ++$aCount;
  1782. }
  1783. }
  1784. // Return
  1785. if ($aCount > 0) {
  1786. $summerA *= $aCount;
  1787. $summerB *= $summerB;
  1788. $returnValue = ($summerA - $summerB) / ($aCount * $aCount);
  1789. }
  1790. return $returnValue;
  1791. } // function VARP()
  1792. /**
  1793. * VARPA
  1794. *
  1795. * Calculates variance based on the entire population, including numbers, text, and logical values
  1796. *
  1797. * Excel Function:
  1798. * VARPA(value1[,value2[, ...]])
  1799. *
  1800. * @access public
  1801. * @category Statistical Functions
  1802. * @param mixed $arg,... Data values
  1803. * @return float
  1804. */
  1805. public static function VARPA() {
  1806. // Return value
  1807. $returnValue = self::$_errorCodes['divisionbyzero'];
  1808. $summerA = $summerB = 0;
  1809. // Loop through arguments
  1810. $aArgs = self::flattenArrayIndexed(func_get_args());
  1811. $aCount = 0;
  1812. foreach ($aArgs as $k => $arg) {
  1813. if ((is_string($arg)) &&
  1814. (self::isValue($k))) {
  1815. return self::$_errorCodes['value'];
  1816. } elseif ((is_string($arg)) &&
  1817. (!self::isMatrixValue($k))) {
  1818. } else {
  1819. // Is it a numeric value?
  1820. if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) {
  1821. if (is_bool($arg)) {
  1822. $arg = (integer) $arg;
  1823. } elseif (is_string($arg)) {
  1824. $arg = 0;
  1825. }
  1826. $summerA += ($arg * $arg);
  1827. $summerB += $arg;
  1828. ++$aCount;
  1829. }
  1830. }
  1831. }
  1832. // Return
  1833. if ($aCount > 0) {
  1834. $summerA *= $aCount;
  1835. $summerB *= $summerB;
  1836. $returnValue = ($summerA - $summerB) / ($aCount * $aCount);
  1837. }
  1838. return $returnValue;
  1839. } // function VARPA()
  1840. /**
  1841. * RANK
  1842. *
  1843. * Returns the rank of a number in a list of numbers.
  1844. *
  1845. * @param number The number whose rank you want to find.
  1846. * @param array of number An array of, or a reference to, a list of numbers.
  1847. * @param mixed Order to sort the values in the value set
  1848. * @return float
  1849. */
  1850. public static function RANK($value,$valueSet,$order=0) {
  1851. $value = self::flattenSingleValue($value);
  1852. $valueSet = self::flattenArray($valueSet);
  1853. $order = (is_null($order)) ? 0 : (integer) self::flattenSingleValue($order);
  1854. foreach($valueSet as $key => $valueEntry) {
  1855. if (!is_numeric($valueEntry)) {
  1856. unset($valueSet[$key]);
  1857. }
  1858. }
  1859. if ($order == 0) {
  1860. rsort($valueSet,SORT_NUMERIC);
  1861. } else {
  1862. sort($valueSet,SORT_NUMERIC);
  1863. }
  1864. $pos = array_search($value,$valueSet);
  1865. if ($pos === False) {
  1866. return self::$_errorCodes['na'];
  1867. }
  1868. return ++$pos;
  1869. } // function RANK()
  1870. /**
  1871. * PERCENTRANK
  1872. *
  1873. * Returns the rank of a value in a data set as a percentage of the data set.
  1874. *
  1875. * @param array of number An array of, or a reference to, a list of numbers.
  1876. * @param number The number whose rank you want to find.
  1877. * @param number The number of significant digits for the returned percentage value.
  1878. * @return float
  1879. */
  1880. public static function PERCENTRANK($valueSet,$value,$significance=3) {
  1881. $valueSet = self::flattenArray($valueSet);
  1882. $value = self::flattenSingleValue($value);
  1883. $significance = (is_null($significance)) ? 3 : (integer) self::flattenSingleValue($significance);
  1884. foreach($valueSet as $key => $valueEntry) {
  1885. if (!is_numeric($valueEntry)) {
  1886. unset($valueSet[$key]);
  1887. }
  1888. }
  1889. sort($valueSet,SORT_NUMERIC);
  1890. $valueCount = count($valueSet);
  1891. if ($valueCount == 0) {
  1892. return self::$_errorCodes['num'];
  1893. }
  1894. $valueAdjustor = $valueCount - 1;
  1895. if (($value < $valueSet[0]) || ($value > $valueSet[$valueAdjustor])) {
  1896. return self::$_errorCodes['na'];
  1897. }
  1898. $pos = array_search($value,$valueSet);
  1899. if ($pos === False) {
  1900. $pos = 0;
  1901. $testValue = $valueSet[0];
  1902. while ($testValue < $value) {
  1903. $testValue = $valueSet[++$pos];
  1904. }
  1905. --$pos;
  1906. $pos += (($value - $valueSet[$pos]) / ($testValue - $valueSet[$pos]));
  1907. }
  1908. return round($pos / $valueAdjustor,$significance);
  1909. } // function PERCENTRANK()
  1910. private static function _checkTrendArrays(&$array1,&$array2) {
  1911. if (!is_array($array1)) { $array1 = array($array1); }
  1912. if (!is_array($array2)) { $array2 = array($array2); }
  1913. $array1 = self::flattenArray($array1);
  1914. $array2 = self::flattenArray($array2);
  1915. foreach($array1 as $key => $value) {
  1916. if ((is_bool($value)) || (is_string($value)) || (is_null($value))) {
  1917. unset($array1[$key]);
  1918. unset($array2[$key]);
  1919. }
  1920. }
  1921. foreach($array2 as $key => $value) {
  1922. if ((is_bool($value)) || (is_string($value)) || (is_null($value))) {
  1923. unset($array1[$key]);
  1924. unset($array2[$key]);
  1925. }
  1926. }
  1927. $array1 = array_merge($array1);
  1928. $array2 = array_merge($array2);
  1929. return True;
  1930. } // function _checkTrendArrays()
  1931. /**
  1932. * INTERCEPT
  1933. *
  1934. * Calculates the point at which a line will intersect the y-axis by using existing x-values and y-values.
  1935. *
  1936. * @param array of mixed Data Series Y
  1937. * @param array of mixed Data Series X
  1938. * @return float
  1939. */
  1940. public static function INTERCEPT($yValues,$xValues) {
  1941. if (!self::_checkTrendArrays($yValues,$xValues)) {
  1942. return self::$_errorCodes['value'];
  1943. }
  1944. $yValueCount = count($yValues);
  1945. $xValueCount = count($xValues);
  1946. if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
  1947. return self::$_errorCodes['na'];
  1948. } elseif ($yValueCount == 1) {
  1949. return self::$_errorCodes['divisionbyzero'];
  1950. }
  1951. $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues);
  1952. return $bestFitLinear->getIntersect();
  1953. } // function INTERCEPT()
  1954. /**
  1955. * RSQ
  1956. *
  1957. * Returns the square of the Pearson product moment correlation coefficient through data points in known_y's and known_x's.
  1958. *
  1959. * @param array of mixed Data Series Y
  1960. * @param array of mixed Data Series X
  1961. * @return float
  1962. */
  1963. public static function RSQ($yValues,$xValues) {
  1964. if (!self::_checkTrendArrays($yValues,$xValues)) {
  1965. return self::$_errorCodes['value'];
  1966. }
  1967. $yValueCount = count($yValues);
  1968. $xValueCount = count($xValues);
  1969. if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
  1970. return self::$_errorCodes['na'];
  1971. } elseif ($yValueCount == 1) {
  1972. return self::$_errorCodes['divisionbyzero'];
  1973. }
  1974. $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues);
  1975. return $bestFitLinear->getGoodnessOfFit();
  1976. } // function RSQ()
  1977. /**
  1978. * SLOPE
  1979. *
  1980. * Returns the slope of the linear regression line through data points in known_y's and known_x's.
  1981. *
  1982. * @param array of mixed Data Series Y
  1983. * @param array of mixed Data Series X
  1984. * @return float
  1985. */
  1986. public static function SLOPE($yValues,$xValues) {
  1987. if (!self::_checkTrendArrays($yValues,$xValues)) {
  1988. return self::$_errorCodes['value'];
  1989. }
  1990. $yValueCount = count($yValues);
  1991. $xValueCount = count($xValues);
  1992. if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
  1993. return self::$_errorCodes['na'];
  1994. } elseif ($yValueCount == 1) {
  1995. return self::$_errorCodes['divisionbyzero'];
  1996. }
  1997. $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues);
  1998. return $bestFitLinear->getSlope();
  1999. } // function SLOPE()
  2000. /**
  2001. * STEYX
  2002. *
  2003. * Returns the standard error of the predicted y-value for each x in the regression.
  2004. *
  2005. * @param array of mixed Data Series Y
  2006. * @param array of mixed Data Series X
  2007. * @return float
  2008. */
  2009. public static function STEYX($yValues,$xValues) {
  2010. if (!self::_checkTrendArrays($yValues,$xValues)) {
  2011. return self::$_errorCodes['value'];
  2012. }
  2013. $yValueCount = count($yValues);
  2014. $xValueCount = count($xValues);
  2015. if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
  2016. return self::$_errorCodes['na'];
  2017. } elseif ($yValueCount == 1) {
  2018. return self::$_errorCodes['divisionbyzero'];
  2019. }
  2020. $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues);
  2021. return $bestFitLinear->getStdevOfResiduals();
  2022. } // function STEYX()
  2023. /**
  2024. * COVAR
  2025. *
  2026. * Returns covariance, the average of the products of deviations for each data point pair.
  2027. *
  2028. * @param array of mixed Data Series Y
  2029. * @param array of mixed Data Series X
  2030. * @return float
  2031. */
  2032. public static function COVAR($yValues,$xValues) {
  2033. if (!self::_checkTrendArrays($yValues,$xValues)) {
  2034. return self::$_errorCodes['value'];
  2035. }
  2036. $yValueCount = count($yValues);
  2037. $xValueCount = count($xValues);
  2038. if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
  2039. return self::$_errorCodes['na'];
  2040. } elseif ($yValueCount == 1) {
  2041. return self::$_errorCodes['divisionbyzero'];
  2042. }
  2043. $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues);
  2044. return $bestFitLinear->getCovariance();
  2045. } // function COVAR()
  2046. /**
  2047. * CORREL
  2048. *
  2049. * Returns covariance, the average of the products of deviations for each data point pair.
  2050. *
  2051. * @param array of mixed Data Series Y
  2052. * @param array of mixed Data Series X
  2053. * @return float
  2054. */
  2055. public static function CORREL($yValues,$xValues=null) {
  2056. if ((is_null($xValues)) || (!is_array($yValues)) || (!is_array($xValues))) {
  2057. return self::$_errorCodes['value'];
  2058. }
  2059. if (!self::_checkTrendArrays($yValues,$xValues)) {
  2060. return self::$_errorCodes['value'];
  2061. }
  2062. $yValueCount = count($yValues);
  2063. $xValueCount = count($xValues);
  2064. if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
  2065. return self::$_errorCodes['na'];
  2066. } elseif ($yValueCount == 1) {
  2067. return self::$_errorCodes['divisionbyzero'];
  2068. }
  2069. $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues);
  2070. return $bestFitLinear->getCorrelation();
  2071. } // function CORREL()
  2072. /**
  2073. * LINEST
  2074. *
  2075. * Calculates the statistics for a line by using the "least squares" method to calculate a straight line that best fits your data,
  2076. * and then returns an array that describes the line.
  2077. *
  2078. * @param array of mixed Data Series Y
  2079. * @param array of mixed Data Series X
  2080. * @param boolean A logical value specifying whether to force the intersect to equal 0.
  2081. * @param boolean A logical value specifying whether to return additional regression statistics.
  2082. * @return array
  2083. */
  2084. public static function LINEST($yValues,$xValues=null,$const=True,$stats=False) {
  2085. $const = (is_null($const)) ? True : (boolean) self::flattenSingleValue($const);
  2086. $stats = (is_null($stats)) ? False : (boolean) self::flattenSingleValue($stats);
  2087. if (is_null($xValues)) $xValues = range(1,count(self::flattenArray($yValues)));
  2088. if (!self::_checkTrendArrays($yValues,$xValues)) {
  2089. return self::$_errorCodes['value'];
  2090. }
  2091. $yValueCount = count($yValues);
  2092. $xValueCount = count($xValues);
  2093. if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
  2094. return self::$_errorCodes['na'];
  2095. } elseif ($yValueCount == 1) {
  2096. return 0;
  2097. }
  2098. $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues,$const);
  2099. if ($stats) {
  2100. return array( array( $bestFitLinear->getSlope(),
  2101. $bestFitLinear->getSlopeSE(),
  2102. $bestFitLinear->getGoodnessOfFit(),
  2103. $bestFitLinear->getF(),
  2104. $bestFitLinear->getSSRegression(),
  2105. ),
  2106. array( $bestFitLinear->getIntersect(),
  2107. $bestFitLinear->getIntersectSE(),
  2108. $bestFitLinear->getStdevOfResiduals(),
  2109. $bestFitLinear->getDFResiduals(),
  2110. $bestFitLinear->getSSResiduals()
  2111. )
  2112. );
  2113. } else {
  2114. return array( $bestFitLinear->getSlope(),
  2115. $bestFitLinear->getIntersect()
  2116. );
  2117. }
  2118. } // function LINEST()
  2119. /**
  2120. * LOGEST
  2121. *
  2122. * Calculates an exponential curve that best fits the X and Y data series,
  2123. * and then returns an array that describes the line.
  2124. *
  2125. * @param array of mixed Data Series Y
  2126. * @param array of mixed Data Series X
  2127. * @param boolean A logical value specifying whether to force the intersect to equal 0.
  2128. * @param boolean A logical value specifying whether to return additional regression statistics.
  2129. * @return array
  2130. */
  2131. public static function LOGEST($yValues,$xValues=null,$const=True,$stats=False) {
  2132. $const = (is_null($const)) ? True : (boolean) self::flattenSingleValue($const);
  2133. $stats = (is_null($stats)) ? False : (boolean) self::flattenSingleValue($stats);
  2134. if (is_null($xValues)) $xValues = range(1,count(self::flattenArray($yValues)));
  2135. if (!self::_checkTrendArrays($yValues,$xValues)) {
  2136. return self::$_errorCodes['value'];
  2137. }
  2138. $yValueCount = count($yValues);
  2139. $xValueCount = count($xValues);
  2140. foreach($yValues as $value) {
  2141. if ($value <= 0.0) {
  2142. return self::$_errorCodes['num'];
  2143. }
  2144. }
  2145. if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
  2146. return self::$_errorCodes['na'];
  2147. } elseif ($yValueCount == 1) {
  2148. return 1;
  2149. }
  2150. $bestFitExponential = trendClass::calculate(trendClass::TREND_EXPONENTIAL,$yValues,$xValues,$const);
  2151. if ($stats) {
  2152. return array( array( $bestFitExponential->getSlope(),
  2153. $bestFitExponential->getSlopeSE(),
  2154. $bestFitExponential->getGoodnessOfFit(),
  2155. $bestFitExponential->getF(),
  2156. $bestFitExponential->getSSRegression(),
  2157. ),
  2158. array( $bestFitExponential->getIntersect(),
  2159. $bestFitExponential->getIntersectSE(),
  2160. $bestFitExponential->getStdevOfResiduals(),
  2161. $bestFitExponential->getDFResiduals(),
  2162. $bestFitExponential->getSSResiduals()
  2163. )
  2164. );
  2165. } else {
  2166. return array( $bestFitExponential->getSlope(),
  2167. $bestFitExponential->getIntersect()
  2168. );
  2169. }
  2170. } // function LOGEST()
  2171. /**
  2172. * FORECAST
  2173. *
  2174. * Calculates, or predicts, a future value by using existing values. The predicted value is a y-value for a given x-value.
  2175. *
  2176. * @param float Value of X for which we want to find Y
  2177. * @param array of mixed Data Series Y
  2178. * @param array of mixed Data Series X
  2179. * @return float
  2180. */
  2181. public static function FORECAST($xValue,$yValues,$xValues) {
  2182. $xValue = self::flattenSingleValue($xValue);
  2183. if (!is_numeric($xValue)) {
  2184. return self::$_errorCodes['value'];
  2185. }
  2186. if (!self::_checkTrendArrays($yValues,$xValues)) {
  2187. return self::$_errorCodes['value'];
  2188. }
  2189. $yValueCount = count($yValues);
  2190. $xValueCount = count($xValues);
  2191. if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
  2192. return self::$_errorCodes['na'];
  2193. } elseif ($yValueCount == 1) {
  2194. return self::$_errorCodes['divisionbyzero'];
  2195. }
  2196. $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues);
  2197. return $bestFitLinear->getValueOfYForX($xValue);
  2198. } // function FORECAST()
  2199. /**
  2200. * TREND
  2201. *
  2202. * Returns values along a linear trend
  2203. *
  2204. * @param array of mixed Data Series Y
  2205. * @param array of mixed Data Series X
  2206. * @param array of mixed Values of X for which we want to find Y
  2207. * @param boolean A logical value specifying whether to force the intersect to equal 0.
  2208. * @return array of float
  2209. */
  2210. public static function TREND($yValues,$xValues=array(),$newValues=array(),$const=True) {
  2211. $yValues = self::flattenArray($yValues);
  2212. $xValues = self::flattenArray($xValues);
  2213. $newValues = self::flattenArray($newValues);
  2214. $const = (is_null($const)) ? True : (boolean) self::flattenSingleValue($const);
  2215. $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues,$const);
  2216. if (count($newValues) == 0) {
  2217. $newValues = $bestFitLinear->getXValues();
  2218. }
  2219. $returnArray = array();
  2220. foreach($newValues as $xValue) {
  2221. $returnArray[0][] = $bestFitLinear->getValueOfYForX($xValue);
  2222. }
  2223. return $returnArray;
  2224. } // function TREND()
  2225. /**
  2226. * GROWTH
  2227. *
  2228. * Returns values along a predicted emponential trend
  2229. *
  2230. * @param array of mixed Data Series Y
  2231. * @param array of mixed Data Series X
  2232. * @param array of mixed Values of X for which we want to find Y
  2233. * @param boolean A logical value specifying whether to force the intersect to equal 0.
  2234. * @return array of float
  2235. */
  2236. public static function GROWTH($yValues,$xValues=array(),$newValues=array(),$const=True) {
  2237. $yValues = self::flattenArray($yValues);
  2238. $xValues = self::flattenArray($xValues);
  2239. $newValues = self::flattenArray($newValues);
  2240. $const = (is_null($const)) ? True : (boolean) self::flattenSingleValue($const);
  2241. $bestFitExponential = trendClass::calculate(trendClass::TREND_EXPONENTIAL,$yValues,$xValues,$const);
  2242. if (count($newValues) == 0) {
  2243. $newValues = $bestFitExponential->getXValues();
  2244. }
  2245. $returnArray = array();
  2246. foreach($newValues as $xValue) {
  2247. $returnArray[0][] = $bestFitExponential->getValueOfYForX($xValue);
  2248. }
  2249. return $returnArray;
  2250. } // function GROWTH()
  2251. private static function _romanCut($num, $n) {
  2252. return ($num - ($num % $n ) ) / $n;
  2253. } // function _romanCut()
  2254. public static function ROMAN($aValue, $style=0) {
  2255. $aValue = (integer) self::flattenSingleValue($aValue);
  2256. $style = (is_null($style)) ? 0 : (integer) self::flattenSingleValue($style);
  2257. if ((!is_numeric($aValue)) || ($aValue < 0) || ($aValue >= 4000)) {
  2258. return self::$_errorCodes['value'];
  2259. }
  2260. if ($aValue == 0) {
  2261. return '';
  2262. }
  2263. $mill = Array('', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM');
  2264. $cent = Array('', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM');
  2265. $tens = Array('', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC');
  2266. $ones = Array('', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX');
  2267. $roman = '';
  2268. while ($aValue > 5999) {
  2269. $roman .= 'M';
  2270. $aValue -= 1000;
  2271. }
  2272. $m = self::_romanCut($aValue, 1000); $aValue %= 1000;
  2273. $c = self::_romanCut($aValue, 100); $aValue %= 100;
  2274. $t = self::_romanCut($aValue, 10); $aValue %= 10;
  2275. return $roman.$mill[$m].$cent[$c].$tens[$t].$ones[$aValue];
  2276. } // function ROMAN()
  2277. /**
  2278. * SUBTOTAL
  2279. *
  2280. * Returns a subtotal in a list or database.
  2281. *
  2282. * @param int the number 1 to 11 that specifies which function to
  2283. * use in calculating subtotals within a list.
  2284. * @param array of mixed Data Series
  2285. * @return float
  2286. */
  2287. public static function SUBTOTAL() {
  2288. $aArgs = self::flattenArray(func_get_args());
  2289. // Calculate
  2290. $subtotal = array_shift($aArgs);
  2291. if ((is_numeric($subtotal)) && (!is_string($subtotal))) {
  2292. switch($subtotal) {
  2293. case 1 :
  2294. return self::AVERAGE($aArgs);
  2295. break;
  2296. case 2 :
  2297. return self::COUNT($aArgs);
  2298. break;
  2299. case 3 :
  2300. return self::COUNTA($aArgs);
  2301. break;
  2302. case 4 :
  2303. return self::MAX($aArgs);
  2304. break;
  2305. case 5 :
  2306. return self::MIN($aArgs);
  2307. break;
  2308. case 6 :
  2309. return self::PRODUCT($aArgs);
  2310. break;
  2311. case 7 :
  2312. return self::STDEV($aArgs);
  2313. break;
  2314. case 8 :
  2315. return self::STDEVP($aArgs);
  2316. break;
  2317. case 9 :
  2318. return self::SUM($aArgs);
  2319. break;
  2320. case 10 :
  2321. return self::VARFunc($aArgs);
  2322. break;
  2323. case 11 :
  2324. return self::VARP($aArgs);
  2325. break;
  2326. }
  2327. }
  2328. return self::$_errorCodes['value'];
  2329. } // function SUBTOTAL()
  2330. /**
  2331. * SQRTPI
  2332. *
  2333. * Returns the square root of (number * pi).
  2334. *
  2335. * @param float $number Number
  2336. * @return float Square Root of Number * Pi
  2337. */
  2338. public static function SQRTPI($number) {
  2339. $number = self::flattenSingleValue($number);
  2340. if (is_numeric($number)) {
  2341. if ($number < 0) {
  2342. return self::$_errorCodes['num'];
  2343. }
  2344. return sqrt($number * M_PI) ;
  2345. }
  2346. return self::$_errorCodes['value'];
  2347. } // function SQRTPI()
  2348. /**
  2349. * FACT
  2350. *
  2351. * Returns the factorial of a number.
  2352. *
  2353. * @param float $factVal Factorial Value
  2354. * @return int Factorial
  2355. */
  2356. public static function FACT($factVal) {
  2357. $factVal = self::flattenSingleValue($factVal);
  2358. if (is_numeric($factVal)) {
  2359. if ($factVal < 0) {
  2360. return self::$_errorCodes['num'];
  2361. }
  2362. $factLoop = floor($factVal);
  2363. if (self::$compatibilityMode == self::COMPATIBILITY_GNUMERIC) {
  2364. if ($factVal > $factLoop) {
  2365. return self::$_errorCodes['num'];
  2366. }
  2367. }
  2368. $factorial = 1;
  2369. while ($factLoop > 1) {
  2370. $factorial *= $factLoop--;
  2371. }
  2372. return $factorial ;
  2373. }
  2374. return self::$_errorCodes['value'];
  2375. } // function FACT()
  2376. /**
  2377. * FACTDOUBLE
  2378. *
  2379. * Returns the double factorial of a number.
  2380. *
  2381. * @param float $factVal Factorial Value
  2382. * @return int Double Factorial
  2383. */
  2384. public static function FACTDOUBLE($factVal) {
  2385. $factLoop = floor(self::flattenSingleValue($factVal));
  2386. if (is_numeric($factLoop)) {
  2387. if ($factVal < 0) {
  2388. return self::$_errorCodes['num'];
  2389. }
  2390. $factorial = 1;
  2391. while ($factLoop > 1) {
  2392. $factorial *= $factLoop--;
  2393. --$factLoop;
  2394. }
  2395. return $factorial ;
  2396. }
  2397. return self::$_errorCodes['value'];
  2398. } // function FACTDOUBLE()
  2399. /**
  2400. * MULTINOMIAL
  2401. *
  2402. * Returns the ratio of the factorial of a sum of values to the product of factorials.
  2403. *
  2404. * @param array of mixed Data Series
  2405. * @return float
  2406. */
  2407. public static function MULTINOMIAL() {
  2408. // Loop through arguments
  2409. $aArgs = self::flattenArray(func_get_args());
  2410. $summer = 0;
  2411. $divisor = 1;
  2412. foreach ($aArgs as $arg) {
  2413. // Is it a numeric value?
  2414. if (is_numeric($arg)) {
  2415. if ($arg < 1) {
  2416. return self::$_errorCodes['num'];
  2417. }
  2418. $summer += floor($arg);
  2419. $divisor *= self::FACT($arg);
  2420. } else {
  2421. return self::$_errorCodes['value'];
  2422. }
  2423. }
  2424. // Return
  2425. if ($summer > 0) {
  2426. $summer = self::FACT($summer);
  2427. return $summer / $divisor;
  2428. }
  2429. return 0;
  2430. } // function MULTINOMIAL()
  2431. /**
  2432. * CEILING
  2433. *
  2434. * Returns number rounded up, away from zero, to the nearest multiple of significance.
  2435. *
  2436. * @param float $number Number to round
  2437. * @param float $significance Significance
  2438. * @return float Rounded Number
  2439. */
  2440. public static function CEILING($number,$significance=null) {
  2441. $number = self::flattenSingleValue($number);
  2442. $significance = self::flattenSingleValue($significance);
  2443. if ((is_null($significance)) && (self::$compatibilityMode == self::COMPATIBILITY_GNUMERIC)) {
  2444. $significance = $number/abs($number);
  2445. }
  2446. if ((is_numeric($number)) && (is_numeric($significance))) {
  2447. if (self::SIGN($number) == self::SIGN($significance)) {
  2448. if ($significance == 0.0) {
  2449. return 0;
  2450. }
  2451. return ceil($number / $significance) * $significance;
  2452. } else {
  2453. return self::$_errorCodes['num'];
  2454. }
  2455. }
  2456. return self::$_errorCodes['value'];
  2457. } // function CEILING()
  2458. /**
  2459. * EVEN
  2460. *
  2461. * Returns number rounded up to the nearest even integer.
  2462. *
  2463. * @param float $number Number to round
  2464. * @return int Rounded Number
  2465. */
  2466. public static function EVEN($number) {
  2467. $number = self::flattenSingleValue($number);
  2468. if (is_numeric($number)) {
  2469. $significance = 2 * self::SIGN($number);
  2470. return self::CEILING($number,$significance);
  2471. }
  2472. return self::$_errorCodes['value'];
  2473. } // function EVEN()
  2474. /**
  2475. * ODD
  2476. *
  2477. * Returns number rounded up to the nearest odd integer.
  2478. *
  2479. * @param float $number Number to round
  2480. * @return int Rounded Number
  2481. */
  2482. public static function ODD($number) {
  2483. $number = self::flattenSingleValue($number);
  2484. if (is_numeric($number)) {
  2485. $significance = self::SIGN($number);
  2486. if ($significance == 0) {
  2487. return 1;
  2488. }
  2489. $result = self::CEILING($number,$significance);
  2490. if (self::IS_EVEN($result)) {
  2491. $result += $significance;
  2492. }
  2493. return $result;
  2494. }
  2495. return self::$_errorCodes['value'];
  2496. } // function ODD()
  2497. /**
  2498. * INTVALUE
  2499. *
  2500. * Casts a floating point value to an integer
  2501. *
  2502. * @param float $number Number to cast to an integer
  2503. * @return integer Integer value
  2504. */
  2505. public static function INTVALUE($number) {
  2506. $number = self::flattenSingleValue($number);
  2507. if (is_numeric($number)) {
  2508. return (int) floor($number);
  2509. }
  2510. return self::$_errorCodes['value'];
  2511. } // function INTVALUE()
  2512. /**
  2513. * ROUNDUP
  2514. *
  2515. * Rounds a number up to a specified number of decimal places
  2516. *
  2517. * @param float $number Number to round
  2518. * @param int $digits Number of digits to which you want to round $number
  2519. * @return float Rounded Number
  2520. */
  2521. public static function ROUNDUP($number,$digits) {
  2522. $number = self::flattenSingleValue($number);
  2523. $digits = self::flattenSingleValue($digits);
  2524. if ((is_numeric($number)) && (is_numeric($digits))) {
  2525. $significance = pow(10,$digits);
  2526. if ($number < 0.0) {
  2527. return floor($number * $significance) / $significance;
  2528. } else {
  2529. return ceil($number * $significance) / $significance;
  2530. }
  2531. }
  2532. return self::$_errorCodes['value'];
  2533. } // function ROUNDUP()
  2534. /**
  2535. * ROUNDDOWN
  2536. *
  2537. * Rounds a number down to a specified number of decimal places
  2538. *
  2539. * @param float $number Number to round
  2540. * @param int $digits Number of digits to which you want to round $number
  2541. * @return float Rounded Number
  2542. */
  2543. public static function ROUNDDOWN($number,$digits) {
  2544. $number = self::flattenSingleValue($number);
  2545. $digits = self::flattenSingleValue($digits);
  2546. if ((is_numeric($number)) && (is_numeric($digits))) {
  2547. $significance = pow(10,$digits);
  2548. if ($number < 0.0) {
  2549. return ceil($number * $significance) / $significance;
  2550. } else {
  2551. return floor($number * $significance) / $significance;
  2552. }
  2553. }
  2554. return self::$_errorCodes['value'];
  2555. } // function ROUNDDOWN()
  2556. /**
  2557. * MROUND
  2558. *
  2559. * Rounds a number to the nearest multiple of a specified value
  2560. *
  2561. * @param float $number Number to round
  2562. * @param int $multiple Multiple to which you want to round $number
  2563. * @return float Rounded Number
  2564. */
  2565. public static function MROUND($number,$multiple) {
  2566. $number = self::flattenSingleValue($number);
  2567. $multiple = self::flattenSingleValue($multiple);
  2568. if ((is_numeric($number)) && (is_numeric($multiple))) {
  2569. if ($multiple == 0) {
  2570. return 0;
  2571. }
  2572. if ((self::SIGN($number)) == (self::SIGN($multiple))) {
  2573. $multiplier = 1 / $multiple;
  2574. return round($number * $multiplier) / $multiplier;
  2575. }
  2576. return self::$_errorCodes['num'];
  2577. }
  2578. return self::$_errorCodes['value'];
  2579. } // function MROUND()
  2580. /**
  2581. * SIGN
  2582. *
  2583. * Determines the sign of a number. Returns 1 if the number is positive, zero (0)
  2584. * if the number is 0, and -1 if the number is negative.
  2585. *
  2586. * @param float $number Number to round
  2587. * @return int sign value
  2588. */
  2589. public static function SIGN($number) {
  2590. $number = self::flattenSingleValue($number);
  2591. if (is_numeric($number)) {
  2592. if ($number == 0.0) {
  2593. return 0;
  2594. }
  2595. return $number / abs($number);
  2596. }
  2597. return self::$_errorCodes['value'];
  2598. } // function SIGN()
  2599. /**
  2600. * FLOOR
  2601. *
  2602. * Rounds number down, toward zero, to the nearest multiple of significance.
  2603. *
  2604. * @param float $number Number to round
  2605. * @param float $significance Significance
  2606. * @return float Rounded Number
  2607. */
  2608. public static function FLOOR($number,$significance=null) {
  2609. $number = self::flattenSingleValue($number);
  2610. $significance = self::flattenSingleValue($significance);
  2611. if ((is_null($significance)) && (self::$compatibilityMode == self::COMPATIBILITY_GNUMERIC)) {
  2612. $significance = $number/abs($number);
  2613. }
  2614. if ((is_numeric($number)) && (is_numeric($significance))) {
  2615. if ((float) $significance == 0.0) {
  2616. return self::$_errorCodes['divisionbyzero'];
  2617. }
  2618. if (self::SIGN($number) == self::SIGN($significance)) {
  2619. return floor($number / $significance) * $significance;
  2620. } else {
  2621. return self::$_errorCodes['num'];
  2622. }
  2623. }
  2624. return self::$_errorCodes['value'];
  2625. } // function FLOOR()
  2626. /**
  2627. * PERMUT
  2628. *
  2629. * Returns the number of permutations for a given number of objects that can be
  2630. * selected from number objects. A permutation is any set or subset of objects or
  2631. * events where internal order is significant. Permutations are different from
  2632. * combinations, for which the internal order is not significant. Use this function
  2633. * for lottery-style probability calculations.
  2634. *
  2635. * @param int $numObjs Number of different objects
  2636. * @param int $numInSet Number of objects in each permutation
  2637. * @return int Number of permutations
  2638. */
  2639. public static function PERMUT($numObjs,$numInSet) {
  2640. $numObjs = self::flattenSingleValue($numObjs);
  2641. $numInSet = self::flattenSingleValue($numInSet);
  2642. if ((is_numeric($numObjs)) && (is_numeric($numInSet))) {
  2643. $numInSet = floor($numInSet);
  2644. if ($numObjs < $numInSet) {
  2645. return self::$_errorCodes['num'];
  2646. }
  2647. return round(self::FACT($numObjs) / self::FACT($numObjs - $numInSet));
  2648. }
  2649. return self::$_errorCodes['value'];
  2650. } // function PERMUT()
  2651. /**
  2652. * COMBIN
  2653. *
  2654. * Returns the number of combinations for a given number of items. Use COMBIN to
  2655. * determine the total possible number of groups for a given number of items.
  2656. *
  2657. * @param int $numObjs Number of different objects
  2658. * @param int $numInSet Number of objects in each combination
  2659. * @return int Number of combinations
  2660. */
  2661. public static function COMBIN($numObjs,$numInSet) {
  2662. $numObjs = self::flattenSingleValue($numObjs);
  2663. $numInSet = self::flattenSingleValue($numInSet);
  2664. if ((is_numeric($numObjs)) && (is_numeric($numInSet))) {
  2665. if ($numObjs < $numInSet) {
  2666. return self::$_errorCodes['num'];
  2667. } elseif ($numInSet < 0) {
  2668. return self::$_errorCodes['num'];
  2669. }
  2670. return round(self::FACT($numObjs) / self::FACT($numObjs - $numInSet)) / self::FACT($numInSet);
  2671. }
  2672. return self::$_errorCodes['value'];
  2673. } // function COMBIN()
  2674. /**
  2675. * SERIESSUM
  2676. *
  2677. * Returns the sum of a power series
  2678. *
  2679. * @param float $x Input value to the power series
  2680. * @param float $n Initial power to which you want to raise $x
  2681. * @param float $m Step by which to increase $n for each term in the series
  2682. * @param array of mixed Data Series
  2683. * @return float
  2684. */
  2685. public static function SERIESSUM() {
  2686. // Return value
  2687. $returnValue = 0;
  2688. // Loop through arguments
  2689. $aArgs = self::flattenArray(func_get_args());
  2690. $x = array_shift($aArgs);
  2691. $n = array_shift($aArgs);
  2692. $m = array_shift($aArgs);
  2693. if ((is_numeric($x)) && (is_numeric($n)) && (is_numeric($m))) {
  2694. // Calculate
  2695. $i = 0;
  2696. foreach($aArgs as $arg) {
  2697. // Is it a numeric value?
  2698. if ((is_numeric($arg)) && (!is_string($arg))) {
  2699. $returnValue += $arg * pow($x,$n + ($m * $i++));
  2700. } else {
  2701. return self::$_errorCodes['value'];
  2702. }
  2703. }
  2704. // Return
  2705. return $returnValue;
  2706. }
  2707. return self::$_errorCodes['value'];
  2708. } // function SERIESSUM()
  2709. /**
  2710. * STANDARDIZE
  2711. *
  2712. * Returns a normalized value from a distribution characterized by mean and standard_dev.
  2713. *
  2714. * @param float $value Value to normalize
  2715. * @param float $mean Mean Value
  2716. * @param float $stdDev Standard Deviation
  2717. * @return float Standardized value
  2718. */
  2719. public static function STANDARDIZE($value,$mean,$stdDev) {
  2720. $value = self::flattenSingleValue($value);
  2721. $mean = self::flattenSingleValue($mean);
  2722. $stdDev = self::flattenSingleValue($stdDev);
  2723. if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
  2724. if ($stdDev <= 0) {
  2725. return self::$_errorCodes['num'];
  2726. }
  2727. return ($value - $mean) / $stdDev ;
  2728. }
  2729. return self::$_errorCodes['value'];
  2730. } // function STANDARDIZE()
  2731. //
  2732. // Private method to return an array of the factors of the input value
  2733. //
  2734. private static function _factors($value) {
  2735. $startVal = floor(sqrt($value));
  2736. $factorArray = array();
  2737. for ($i = $startVal; $i > 1; --$i) {
  2738. if (($value % $i) == 0) {
  2739. $factorArray = array_merge($factorArray,self::_factors($value / $i));
  2740. $factorArray = array_merge($factorArray,self::_factors($i));
  2741. if ($i <= sqrt($value)) {
  2742. break;
  2743. }
  2744. }
  2745. }
  2746. if (count($factorArray) > 0) {
  2747. rsort($factorArray);
  2748. return $factorArray;
  2749. } else {
  2750. return array((integer) $value);
  2751. }
  2752. } // function _factors()
  2753. /**
  2754. * LCM
  2755. *
  2756. * Returns the lowest common multiplier of a series of numbers
  2757. *
  2758. * @param $array Values to calculate the Lowest Common Multiplier
  2759. * @return int Lowest Common Multiplier
  2760. */
  2761. public static function LCM() {
  2762. $aArgs = self::flattenArray(func_get_args());
  2763. $returnValue = 1;
  2764. $allPoweredFactors = array();
  2765. foreach($aArgs as $value) {
  2766. if (!is_numeric($value)) {
  2767. return self::$_errorCodes['value'];
  2768. }
  2769. if ($value == 0) {
  2770. return 0;
  2771. } elseif ($value < 0) {
  2772. return self::$_errorCodes['num'];
  2773. }
  2774. $myFactors = self::_factors(floor($value));
  2775. $myCountedFactors = array_count_values($myFactors);
  2776. $myPoweredFactors = array();
  2777. foreach($myCountedFactors as $myCountedFactor => $myCountedPower) {
  2778. $myPoweredFactors[$myCountedFactor] = pow($myCountedFactor,$myCountedPower);
  2779. }
  2780. foreach($myPoweredFactors as $myPoweredValue => $myPoweredFactor) {
  2781. if (array_key_exists($myPoweredValue,$allPoweredFactors)) {
  2782. if ($allPoweredFactors[$myPoweredValue] < $myPoweredFactor) {
  2783. $allPoweredFactors[$myPoweredValue] = $myPoweredFactor;
  2784. }
  2785. } else {
  2786. $allPoweredFactors[$myPoweredValue] = $myPoweredFactor;
  2787. }
  2788. }
  2789. }
  2790. foreach($allPoweredFactors as $allPoweredFactor) {
  2791. $returnValue *= (integer) $allPoweredFactor;
  2792. }
  2793. return $returnValue;
  2794. } // function LCM()
  2795. /**
  2796. * GCD
  2797. *
  2798. * Returns the greatest common divisor of a series of numbers
  2799. *
  2800. * @param $array Values to calculate the Greatest Common Divisor
  2801. * @return int Greatest Common Divisor
  2802. */
  2803. public static function GCD() {
  2804. $aArgs = self::flattenArray(func_get_args());
  2805. $returnValue = 1;
  2806. $allPoweredFactors = array();
  2807. foreach($aArgs as $value) {
  2808. if ($value == 0) {
  2809. break;
  2810. }
  2811. $myFactors = self::_factors($value);
  2812. $myCountedFactors = array_count_values($myFactors);
  2813. $allValuesFactors[] = $myCountedFactors;
  2814. }
  2815. $allValuesCount = count($allValuesFactors);
  2816. $mergedArray = $allValuesFactors[0];
  2817. for ($i=1;$i < $allValuesCount; ++$i) {
  2818. $mergedArray = array_intersect_key($mergedArray,$allValuesFactors[$i]);
  2819. }
  2820. $mergedArrayValues = count($mergedArray);
  2821. if ($mergedArrayValues == 0) {
  2822. return $returnValue;
  2823. } elseif ($mergedArrayValues > 1) {
  2824. foreach($mergedArray as $mergedKey => $mergedValue) {
  2825. foreach($allValuesFactors as $highestPowerTest) {
  2826. foreach($highestPowerTest as $testKey => $testValue) {
  2827. if (($testKey == $mergedKey) && ($testValue < $mergedValue)) {
  2828. $mergedArray[$mergedKey] = $testValue;
  2829. $mergedValue = $testValue;
  2830. }
  2831. }
  2832. }
  2833. }
  2834. $returnValue = 1;
  2835. foreach($mergedArray as $key => $value) {
  2836. $returnValue *= pow($key,$value);
  2837. }
  2838. return $returnValue;
  2839. } else {
  2840. $keys = array_keys($mergedArray);
  2841. $key = $keys[0];
  2842. $value = $mergedArray[$key];
  2843. foreach($allValuesFactors as $testValue) {
  2844. foreach($testValue as $mergedKey => $mergedValue) {
  2845. if (($mergedKey == $key) && ($mergedValue < $value)) {
  2846. $value = $mergedValue;
  2847. }
  2848. }
  2849. }
  2850. return pow($key,$value);
  2851. }
  2852. } // function GCD()
  2853. /**
  2854. * BINOMDIST
  2855. *
  2856. * Returns the individual term binomial distribution probability. Use BINOMDIST in problems with
  2857. * a fixed number of tests or trials, when the outcomes of any trial are only success or failure,
  2858. * when trials are independent, and when the probability of success is constant throughout the
  2859. * experiment. For example, BINOMDIST can calculate the probability that two of the next three
  2860. * babies born are male.
  2861. *
  2862. * @param float $value Number of successes in trials
  2863. * @param float $trials Number of trials
  2864. * @param float $probability Probability of success on each trial
  2865. * @param boolean $cumulative
  2866. * @return float
  2867. *
  2868. * @todo Cumulative distribution function
  2869. *
  2870. */
  2871. public static function BINOMDIST($value, $trials, $probability, $cumulative) {
  2872. $value = floor(self::flattenSingleValue($value));
  2873. $trials = floor(self::flattenSingleValue($trials));
  2874. $probability = self::flattenSingleValue($probability);
  2875. if ((is_numeric($value)) && (is_numeric($trials)) && (is_numeric($probability))) {
  2876. if (($value < 0) || ($value > $trials)) {
  2877. return self::$_errorCodes['num'];
  2878. }
  2879. if (($probability < 0) || ($probability > 1)) {
  2880. return self::$_errorCodes['num'];
  2881. }
  2882. if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
  2883. if ($cumulative) {
  2884. $summer = 0;
  2885. for ($i = 0; $i <= $value; ++$i) {
  2886. $summer += self::COMBIN($trials,$i) * pow($probability,$i) * pow(1 - $probability,$trials - $i);
  2887. }
  2888. return $summer;
  2889. } else {
  2890. return self::COMBIN($trials,$value) * pow($probability,$value) * pow(1 - $probability,$trials - $value) ;
  2891. }
  2892. }
  2893. }
  2894. return self::$_errorCodes['value'];
  2895. } // function BINOMDIST()
  2896. /**
  2897. * NEGBINOMDIST
  2898. *
  2899. * Returns the negative binomial distribution. NEGBINOMDIST returns the probability that
  2900. * there will be number_f failures before the number_s-th success, when the constant
  2901. * probability of a success is probability_s. This function is similar to the binomial
  2902. * distribution, except that the number of successes is fixed, and the number of trials is
  2903. * variable. Like the binomial, trials are assumed to be independent.
  2904. *
  2905. * @param float $failures Number of Failures
  2906. * @param float $successes Threshold number of Successes
  2907. * @param float $probability Probability of success on each trial
  2908. * @return float
  2909. *
  2910. */
  2911. public static function NEGBINOMDIST($failures, $successes, $probability) {
  2912. $failures = floor(self::flattenSingleValue($failures));
  2913. $successes = floor(self::flattenSingleValue($successes));
  2914. $probability = self::flattenSingleValue($probability);
  2915. if ((is_numeric($failures)) && (is_numeric($successes)) && (is_numeric($probability))) {
  2916. if (($failures < 0) || ($successes < 1)) {
  2917. return self::$_errorCodes['num'];
  2918. }
  2919. if (($probability < 0) || ($probability > 1)) {
  2920. return self::$_errorCodes['num'];
  2921. }
  2922. if (self::$compatibilityMode == self::COMPATIBILITY_GNUMERIC) {
  2923. if (($failures + $successes - 1) <= 0) {
  2924. return self::$_errorCodes['num'];
  2925. }
  2926. }
  2927. return (self::COMBIN($failures + $successes - 1,$successes - 1)) * (pow($probability,$successes)) * (pow(1 - $probability,$failures)) ;
  2928. }
  2929. return self::$_errorCodes['value'];
  2930. } // function NEGBINOMDIST()
  2931. /**
  2932. * CRITBINOM
  2933. *
  2934. * Returns the smallest value for which the cumulative binomial distribution is greater
  2935. * than or equal to a criterion value
  2936. *
  2937. * See http://support.microsoft.com/kb/828117/ for details of the algorithm used
  2938. *
  2939. * @param float $trials number of Bernoulli trials
  2940. * @param float $probability probability of a success on each trial
  2941. * @param float $alpha criterion value
  2942. * @return int
  2943. *
  2944. * @todo Warning. This implementation differs from the algorithm detailed on the MS
  2945. * web site in that $CumPGuessMinus1 = $CumPGuess - 1 rather than $CumPGuess - $PGuess
  2946. * This eliminates a potential endless loop error, but may have an adverse affect on the
  2947. * accuracy of the function (although all my tests have so far returned correct results).
  2948. *
  2949. */
  2950. public static function CRITBINOM($trials, $probability, $alpha) {
  2951. $trials = floor(self::flattenSingleValue($trials));
  2952. $probability = self::flattenSingleValue($probability);
  2953. $alpha = self::flattenSingleValue($alpha);
  2954. if ((is_numeric($trials)) && (is_numeric($probability)) && (is_numeric($alpha))) {
  2955. if ($trials < 0) {
  2956. return self::$_errorCodes['num'];
  2957. }
  2958. if (($probability < 0) || ($probability > 1)) {
  2959. return self::$_errorCodes['num'];
  2960. }
  2961. if (($alpha < 0) || ($alpha > 1)) {
  2962. return self::$_errorCodes['num'];
  2963. }
  2964. if ($alpha <= 0.5) {
  2965. $t = sqrt(log(1 / ($alpha * $alpha)));
  2966. $trialsApprox = 0 - ($t + (2.515517 + 0.802853 * $t + 0.010328 * $t * $t) / (1 + 1.432788 * $t + 0.189269 * $t * $t + 0.001308 * $t * $t * $t));
  2967. } else {
  2968. $t = sqrt(log(1 / pow(1 - $alpha,2)));
  2969. $trialsApprox = $t - (2.515517 + 0.802853 * $t + 0.010328 * $t * $t) / (1 + 1.432788 * $t + 0.189269 * $t * $t + 0.001308 * $t * $t * $t);
  2970. }
  2971. $Guess = floor($trials * $probability + $trialsApprox * sqrt($trials * $probability * (1 - $probability)));
  2972. if ($Guess < 0) {
  2973. $Guess = 0;
  2974. } elseif ($Guess > $trials) {
  2975. $Guess = $trials;
  2976. }
  2977. $TotalUnscaledProbability = $UnscaledPGuess = $UnscaledCumPGuess = 0.0;
  2978. $EssentiallyZero = 10e-12;
  2979. $m = floor($trials * $probability);
  2980. ++$TotalUnscaledProbability;
  2981. if ($m == $Guess) { ++$UnscaledPGuess; }
  2982. if ($m <= $Guess) { ++$UnscaledCumPGuess; }
  2983. $PreviousValue = 1;
  2984. $Done = False;
  2985. $k = $m + 1;
  2986. while ((!$Done) && ($k <= $trials)) {
  2987. $CurrentValue = $PreviousValue * ($trials - $k + 1) * $probability / ($k * (1 - $probability));
  2988. $TotalUnscaledProbability += $CurrentValue;
  2989. if ($k == $Guess) { $UnscaledPGuess += $CurrentValue; }
  2990. if ($k <= $Guess) { $UnscaledCumPGuess += $CurrentValue; }
  2991. if ($CurrentValue <= $EssentiallyZero) { $Done = True; }
  2992. $PreviousValue = $CurrentValue;
  2993. ++$k;
  2994. }
  2995. $PreviousValue = 1;
  2996. $Done = False;
  2997. $k = $m - 1;
  2998. while ((!$Done) && ($k >= 0)) {
  2999. $CurrentValue = $PreviousValue * $k + 1 * (1 - $probability) / (($trials - $k) * $probability);
  3000. $TotalUnscaledProbability += $CurrentValue;
  3001. if ($k == $Guess) { $UnscaledPGuess += $CurrentValue; }
  3002. if ($k <= $Guess) { $UnscaledCumPGuess += $CurrentValue; }
  3003. if ($CurrentValue <= $EssentiallyZero) { $Done = True; }
  3004. $PreviousValue = $CurrentValue;
  3005. --$k;
  3006. }
  3007. $PGuess = $UnscaledPGuess / $TotalUnscaledProbability;
  3008. $CumPGuess = $UnscaledCumPGuess / $TotalUnscaledProbability;
  3009. // $CumPGuessMinus1 = $CumPGuess - $PGuess;
  3010. $CumPGuessMinus1 = $CumPGuess - 1;
  3011. while (True) {
  3012. if (($CumPGuessMinus1 < $alpha) && ($CumPGuess >= $alpha)) {
  3013. return $Guess;
  3014. } elseif (($CumPGuessMinus1 < $alpha) && ($CumPGuess < $alpha)) {
  3015. $PGuessPlus1 = $PGuess * ($trials - $Guess) * $probability / $Guess / (1 - $probability);
  3016. $CumPGuessMinus1 = $CumPGuess;
  3017. $CumPGuess = $CumPGuess + $PGuessPlus1;
  3018. $PGuess = $PGuessPlus1;
  3019. ++$Guess;
  3020. } elseif (($CumPGuessMinus1 >= $alpha) && ($CumPGuess >= $alpha)) {
  3021. $PGuessMinus1 = $PGuess * $Guess * (1 - $probability) / ($trials - $Guess + 1) / $probability;
  3022. $CumPGuess = $CumPGuessMinus1;
  3023. $CumPGuessMinus1 = $CumPGuessMinus1 - $PGuess;
  3024. $PGuess = $PGuessMinus1;
  3025. --$Guess;
  3026. }
  3027. }
  3028. }
  3029. return self::$_errorCodes['value'];
  3030. } // function CRITBINOM()
  3031. /**
  3032. * CHIDIST
  3033. *
  3034. * Returns the one-tailed probability of the chi-squared distribution.
  3035. *
  3036. * @param float $value Value for the function
  3037. * @param float $degrees degrees of freedom
  3038. * @return float
  3039. */
  3040. public static function CHIDIST($value, $degrees) {
  3041. $value = self::flattenSingleValue($value);
  3042. $degrees = floor(self::flattenSingleValue($degrees));
  3043. if ((is_numeric($value)) && (is_numeric($degrees))) {
  3044. if ($degrees < 1) {
  3045. return self::$_errorCodes['num'];
  3046. }
  3047. if ($value < 0) {
  3048. if (self::$compatibilityMode == self::COMPATIBILITY_GNUMERIC) {
  3049. return 1;
  3050. }
  3051. return self::$_errorCodes['num'];
  3052. }
  3053. return 1 - (self::_incompleteGamma($degrees/2,$value/2) / self::_gamma($degrees/2));
  3054. }
  3055. return self::$_errorCodes['value'];
  3056. } // function CHIDIST()
  3057. /**
  3058. * CHIINV
  3059. *
  3060. * Returns the one-tailed probability of the chi-squared distribution.
  3061. *
  3062. * @param float $probability Probability for the function
  3063. * @param float $degrees degrees of freedom
  3064. * @return float
  3065. */
  3066. public static function CHIINV($probability, $degrees) {
  3067. $probability = self::flattenSingleValue($probability);
  3068. $degrees = floor(self::flattenSingleValue($degrees));
  3069. if ((is_numeric($probability)) && (is_numeric($degrees))) {
  3070. $xLo = 100;
  3071. $xHi = 0;
  3072. $x = $xNew = 1;
  3073. $dx = 1;
  3074. $i = 0;
  3075. while ((abs($dx) > PRECISION) && ($i++ < MAX_ITERATIONS)) {
  3076. // Apply Newton-Raphson step
  3077. $result = self::CHIDIST($x, $degrees);
  3078. $error = $result - $probability;
  3079. if ($error == 0.0) {
  3080. $dx = 0;
  3081. } elseif ($error < 0.0) {
  3082. $xLo = $x;
  3083. } else {
  3084. $xHi = $x;
  3085. }
  3086. // Avoid division by zero
  3087. if ($result != 0.0) {
  3088. $dx = $error / $result;
  3089. $xNew = $x - $dx;
  3090. }
  3091. // If the NR fails to converge (which for example may be the
  3092. // case if the initial guess is too rough) we apply a bisection
  3093. // step to determine a more narrow interval around the root.
  3094. if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) {
  3095. $xNew = ($xLo + $xHi) / 2;
  3096. $dx = $xNew - $x;
  3097. }
  3098. $x = $xNew;
  3099. }
  3100. if ($i == MAX_ITERATIONS) {
  3101. return self::$_errorCodes['na'];
  3102. }
  3103. return round($x,12);
  3104. }
  3105. return self::$_errorCodes['value'];
  3106. } // function CHIINV()
  3107. /**
  3108. * EXPONDIST
  3109. *
  3110. * Returns the exponential distribution. Use EXPONDIST to model the time between events,
  3111. * such as how long an automated bank teller takes to deliver cash. For example, you can
  3112. * use EXPONDIST to determine the probability that the process takes at most 1 minute.
  3113. *
  3114. * @param float $value Value of the function
  3115. * @param float $lambda The parameter value
  3116. * @param boolean $cumulative
  3117. * @return float
  3118. */
  3119. public static function EXPONDIST($value, $lambda, $cumulative) {
  3120. $value = self::flattenSingleValue($value);
  3121. $lambda = self::flattenSingleValue($lambda);
  3122. $cumulative = self::flattenSingleValue($cumulative);
  3123. if ((is_numeric($value)) && (is_numeric($lambda))) {
  3124. if (($value < 0) || ($lambda < 0)) {
  3125. return self::$_errorCodes['num'];
  3126. }
  3127. if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
  3128. if ($cumulative) {
  3129. return 1 - exp(0-$value*$lambda);
  3130. } else {
  3131. return $lambda * exp(0-$value*$lambda);
  3132. }
  3133. }
  3134. }
  3135. return self::$_errorCodes['value'];
  3136. } // function EXPONDIST()
  3137. /**
  3138. * FISHER
  3139. *
  3140. * Returns the Fisher transformation at x. This transformation produces a function that
  3141. * is normally distributed rather than skewed. Use this function to perform hypothesis
  3142. * testing on the correlation coefficient.
  3143. *
  3144. * @param float $value
  3145. * @return float
  3146. */
  3147. public static function FISHER($value) {
  3148. $value = self::flattenSingleValue($value);
  3149. if (is_numeric($value)) {
  3150. if (($value <= -1) || ($value >= 1)) {
  3151. return self::$_errorCodes['num'];
  3152. }
  3153. return 0.5 * log((1+$value)/(1-$value));
  3154. }
  3155. return self::$_errorCodes['value'];
  3156. } // function FISHER()
  3157. /**
  3158. * FISHERINV
  3159. *
  3160. * Returns the inverse of the Fisher transformation. Use this transformation when
  3161. * analyzing correlations between ranges or arrays of data. If y = FISHER(x), then
  3162. * FISHERINV(y) = x.
  3163. *
  3164. * @param float $value
  3165. * @return float
  3166. */
  3167. public static function FISHERINV($value) {
  3168. $value = self::flattenSingleValue($value);
  3169. if (is_numeric($value)) {
  3170. return (exp(2 * $value) - 1) / (exp(2 * $value) + 1);
  3171. }
  3172. return self::$_errorCodes['value'];
  3173. } // function FISHERINV()
  3174. // Function cache for _logBeta function
  3175. private static $_logBetaCache_p = 0.0;
  3176. private static $_logBetaCache_q = 0.0;
  3177. private static $_logBetaCache_result = 0.0;
  3178. /**
  3179. * The natural logarithm of the beta function.
  3180. * @param p require p>0
  3181. * @param q require q>0
  3182. * @return 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow
  3183. * @author Jaco van Kooten
  3184. */
  3185. private static function _logBeta($p, $q) {
  3186. if ($p != self::$_logBetaCache_p || $q != self::$_logBetaCache_q) {
  3187. self::$_logBetaCache_p = $p;
  3188. self::$_logBetaCache_q = $q;
  3189. if (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > LOG_GAMMA_X_MAX_VALUE)) {
  3190. self::$_logBetaCache_result = 0.0;
  3191. } else {
  3192. self::$_logBetaCache_result = self::_logGamma($p) + self::_logGamma($q) - self::_logGamma($p + $q);
  3193. }
  3194. }
  3195. return self::$_logBetaCache_result;
  3196. } // function _logBeta()
  3197. /**
  3198. * Evaluates of continued fraction part of incomplete beta function.
  3199. * Based on an idea from Numerical Recipes (W.H. Press et al, 1992).
  3200. * @author Jaco van Kooten
  3201. */
  3202. private static function _betaFraction($x, $p, $q) {
  3203. $c = 1.0;
  3204. $sum_pq = $p + $q;
  3205. $p_plus = $p + 1.0;
  3206. $p_minus = $p - 1.0;
  3207. $h = 1.0 - $sum_pq * $x / $p_plus;
  3208. if (abs($h) < XMININ) {
  3209. $h = XMININ;
  3210. }
  3211. $h = 1.0 / $h;
  3212. $frac = $h;
  3213. $m = 1;
  3214. $delta = 0.0;
  3215. while ($m <= MAX_ITERATIONS && abs($delta-1.0) > PRECISION ) {
  3216. $m2 = 2 * $m;
  3217. // even index for d
  3218. $d = $m * ($q - $m) * $x / ( ($p_minus + $m2) * ($p + $m2));
  3219. $h = 1.0 + $d * $h;
  3220. if (abs($h) < XMININ) {
  3221. $h = XMININ;
  3222. }
  3223. $h = 1.0 / $h;
  3224. $c = 1.0 + $d / $c;
  3225. if (abs($c) < XMININ) {
  3226. $c = XMININ;
  3227. }
  3228. $frac *= $h * $c;
  3229. // odd index for d
  3230. $d = -($p + $m) * ($sum_pq + $m) * $x / (($p + $m2) * ($p_plus + $m2));
  3231. $h = 1.0 + $d * $h;
  3232. if (abs($h) < XMININ) {
  3233. $h = XMININ;
  3234. }
  3235. $h = 1.0 / $h;
  3236. $c = 1.0 + $d / $c;
  3237. if (abs($c) < XMININ) {
  3238. $c = XMININ;
  3239. }
  3240. $delta = $h * $c;
  3241. $frac *= $delta;
  3242. ++$m;
  3243. }
  3244. return $frac;
  3245. } // function _betaFraction()
  3246. /**
  3247. * logGamma function
  3248. *
  3249. * @version 1.1
  3250. * @author Jaco van Kooten
  3251. *
  3252. * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher.
  3253. *
  3254. * The natural logarithm of the gamma function. <br />
  3255. * Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz <br />
  3256. * Applied Mathematics Division <br />
  3257. * Argonne National Laboratory <br />
  3258. * Argonne, IL 60439 <br />
  3259. * <p>
  3260. * References:
  3261. * <ol>
  3262. * <li>W. J. Cody and K. E. Hillstrom, 'Chebyshev Approximations for the Natural
  3263. * Logarithm of the Gamma Function,' Math. Comp. 21, 1967, pp. 198-203.</li>
  3264. * <li>K. E. Hillstrom, ANL/AMD Program ANLC366S, DGAMMA/DLGAMA, May, 1969.</li>
  3265. * <li>Hart, Et. Al., Computer Approximations, Wiley and sons, New York, 1968.</li>
  3266. * </ol>
  3267. * </p>
  3268. * <p>
  3269. * From the original documentation:
  3270. * </p>
  3271. * <p>
  3272. * This routine calculates the LOG(GAMMA) function for a positive real argument X.
  3273. * Computation is based on an algorithm outlined in references 1 and 2.
  3274. * The program uses rational functions that theoretically approximate LOG(GAMMA)
  3275. * to at least 18 significant decimal digits. The approximation for X > 12 is from
  3276. * reference 3, while approximations for X < 12.0 are similar to those in reference
  3277. * 1, but are unpublished. The accuracy achieved depends on the arithmetic system,
  3278. * the compiler, the intrinsic functions, and proper selection of the
  3279. * machine-dependent constants.
  3280. * </p>
  3281. * <p>
  3282. * Error returns: <br />
  3283. * The program returns the value XINF for X .LE. 0.0 or when overflow would occur.
  3284. * The computation is believed to be free of underflow and overflow.
  3285. * </p>
  3286. * @return MAX_VALUE for x < 0.0 or when overflow would occur, i.e. x > 2.55E305
  3287. */
  3288. // Function cache for logGamma
  3289. private static $_logGammaCache_result = 0.0;
  3290. private static $_logGammaCache_x = 0.0;
  3291. private static function _logGamma($x) {
  3292. // Log Gamma related constants
  3293. static $lg_d1 = -0.5772156649015328605195174;
  3294. static $lg_d2 = 0.4227843350984671393993777;
  3295. static $lg_d4 = 1.791759469228055000094023;
  3296. static $lg_p1 = array( 4.945235359296727046734888,
  3297. 201.8112620856775083915565,
  3298. 2290.838373831346393026739,
  3299. 11319.67205903380828685045,
  3300. 28557.24635671635335736389,
  3301. 38484.96228443793359990269,
  3302. 26377.48787624195437963534,
  3303. 7225.813979700288197698961 );
  3304. static $lg_p2 = array( 4.974607845568932035012064,
  3305. 542.4138599891070494101986,
  3306. 15506.93864978364947665077,
  3307. 184793.2904445632425417223,
  3308. 1088204.76946882876749847,
  3309. 3338152.967987029735917223,
  3310. 5106661.678927352456275255,
  3311. 3074109.054850539556250927 );
  3312. static $lg_p4 = array( 14745.02166059939948905062,
  3313. 2426813.369486704502836312,
  3314. 121475557.4045093227939592,
  3315. 2663432449.630976949898078,
  3316. 29403789566.34553899906876,
  3317. 170266573776.5398868392998,
  3318. 492612579337.743088758812,
  3319. 560625185622.3951465078242 );
  3320. static $lg_q1 = array( 67.48212550303777196073036,
  3321. 1113.332393857199323513008,
  3322. 7738.757056935398733233834,
  3323. 27639.87074403340708898585,
  3324. 54993.10206226157329794414,
  3325. 61611.22180066002127833352,
  3326. 36351.27591501940507276287,
  3327. 8785.536302431013170870835 );
  3328. static $lg_q2 = array( 183.0328399370592604055942,
  3329. 7765.049321445005871323047,
  3330. 133190.3827966074194402448,
  3331. 1136705.821321969608938755,
  3332. 5267964.117437946917577538,
  3333. 13467014.54311101692290052,
  3334. 17827365.30353274213975932,
  3335. 9533095.591844353613395747 );
  3336. static $lg_q4 = array( 2690.530175870899333379843,
  3337. 639388.5654300092398984238,
  3338. 41355999.30241388052042842,
  3339. 1120872109.61614794137657,
  3340. 14886137286.78813811542398,
  3341. 101680358627.2438228077304,
  3342. 341747634550.7377132798597,
  3343. 446315818741.9713286462081 );
  3344. static $lg_c = array( -0.001910444077728,
  3345. 8.4171387781295e-4,
  3346. -5.952379913043012e-4,
  3347. 7.93650793500350248e-4,
  3348. -0.002777777777777681622553,
  3349. 0.08333333333333333331554247,
  3350. 0.0057083835261 );
  3351. // Rough estimate of the fourth root of logGamma_xBig
  3352. static $lg_frtbig = 2.25e76;
  3353. static $pnt68 = 0.6796875;
  3354. if ($x == self::$_logGammaCache_x) {
  3355. return self::$_logGammaCache_result;
  3356. }
  3357. $y = $x;
  3358. if ($y > 0.0 && $y <= LOG_GAMMA_X_MAX_VALUE) {
  3359. if ($y <= EPS) {
  3360. $res = -log(y);
  3361. } elseif ($y <= 1.5) {
  3362. // ---------------------
  3363. // EPS .LT. X .LE. 1.5
  3364. // ---------------------
  3365. if ($y < $pnt68) {
  3366. $corr = -log($y);
  3367. $xm1 = $y;
  3368. } else {
  3369. $corr = 0.0;
  3370. $xm1 = $y - 1.0;
  3371. }
  3372. if ($y <= 0.5 || $y >= $pnt68) {
  3373. $xden = 1.0;
  3374. $xnum = 0.0;
  3375. for ($i = 0; $i < 8; ++$i) {
  3376. $xnum = $xnum * $xm1 + $lg_p1[$i];
  3377. $xden = $xden * $xm1 + $lg_q1[$i];
  3378. }
  3379. $res = $corr + $xm1 * ($lg_d1 + $xm1 * ($xnum / $xden));
  3380. } else {
  3381. $xm2 = $y - 1.0;
  3382. $xden = 1.0;
  3383. $xnum = 0.0;
  3384. for ($i = 0; $i < 8; ++$i) {
  3385. $xnum = $xnum * $xm2 + $lg_p2[$i];
  3386. $xden = $xden * $xm2 + $lg_q2[$i];
  3387. }
  3388. $res = $corr + $xm2 * ($lg_d2 + $xm2 * ($xnum / $xden));
  3389. }
  3390. } elseif ($y <= 4.0) {
  3391. // ---------------------
  3392. // 1.5 .LT. X .LE. 4.0
  3393. // ---------------------
  3394. $xm2 = $y - 2.0;
  3395. $xden = 1.0;
  3396. $xnum = 0.0;
  3397. for ($i = 0; $i < 8; ++$i) {
  3398. $xnum = $xnum * $xm2 + $lg_p2[$i];
  3399. $xden = $xden * $xm2 + $lg_q2[$i];
  3400. }
  3401. $res = $xm2 * ($lg_d2 + $xm2 * ($xnum / $xden));
  3402. } elseif ($y <= 12.0) {
  3403. // ----------------------
  3404. // 4.0 .LT. X .LE. 12.0
  3405. // ----------------------
  3406. $xm4 = $y - 4.0;
  3407. $xden = -1.0;
  3408. $xnum = 0.0;
  3409. for ($i = 0; $i < 8; ++$i) {
  3410. $xnum = $xnum * $xm4 + $lg_p4[$i];
  3411. $xden = $xden * $xm4 + $lg_q4[$i];
  3412. }
  3413. $res = $lg_d4 + $xm4 * ($xnum / $xden);
  3414. } else {
  3415. // ---------------------------------
  3416. // Evaluate for argument .GE. 12.0
  3417. // ---------------------------------
  3418. $res = 0.0;
  3419. if ($y <= $lg_frtbig) {
  3420. $res = $lg_c[6];
  3421. $ysq = $y * $y;
  3422. for ($i = 0; $i < 6; ++$i)
  3423. $res = $res / $ysq + $lg_c[$i];
  3424. }
  3425. $res /= $y;
  3426. $corr = log($y);
  3427. $res = $res + log(SQRT2PI) - 0.5 * $corr;
  3428. $res += $y * ($corr - 1.0);
  3429. }
  3430. } else {
  3431. // --------------------------
  3432. // Return for bad arguments
  3433. // --------------------------
  3434. $res = MAX_VALUE;
  3435. }
  3436. // ------------------------------
  3437. // Final adjustments and return
  3438. // ------------------------------
  3439. self::$_logGammaCache_x = $x;
  3440. self::$_logGammaCache_result = $res;
  3441. return $res;
  3442. } // function _logGamma()
  3443. /**
  3444. * Beta function.
  3445. *
  3446. * @author Jaco van Kooten
  3447. *
  3448. * @param p require p>0
  3449. * @param q require q>0
  3450. * @return 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow
  3451. */
  3452. private static function _beta($p, $q) {
  3453. if ($p <= 0.0 || $q <= 0.0 || ($p + $q) > LOG_GAMMA_X_MAX_VALUE) {
  3454. return 0.0;
  3455. } else {
  3456. return exp(self::_logBeta($p, $q));
  3457. }
  3458. } // function _beta()
  3459. /**
  3460. * Incomplete beta function
  3461. *
  3462. * @author Jaco van Kooten
  3463. * @author Paul Meagher
  3464. *
  3465. * The computation is based on formulas from Numerical Recipes, Chapter 6.4 (W.H. Press et al, 1992).
  3466. * @param x require 0<=x<=1
  3467. * @param p require p>0
  3468. * @param q require q>0
  3469. * @return 0 if x<0, p<=0, q<=0 or p+q>2.55E305 and 1 if x>1 to avoid errors and over/underflow
  3470. */
  3471. private static function _incompleteBeta($x, $p, $q) {
  3472. if ($x <= 0.0) {
  3473. return 0.0;
  3474. } elseif ($x >= 1.0) {
  3475. return 1.0;
  3476. } elseif (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > LOG_GAMMA_X_MAX_VALUE)) {
  3477. return 0.0;
  3478. }
  3479. $beta_gam = exp((0 - self::_logBeta($p, $q)) + $p * log($x) + $q * log(1.0 - $x));
  3480. if ($x < ($p + 1.0) / ($p + $q + 2.0)) {
  3481. return $beta_gam * self::_betaFraction($x, $p, $q) / $p;
  3482. } else {
  3483. return 1.0 - ($beta_gam * self::_betaFraction(1 - $x, $q, $p) / $q);
  3484. }
  3485. } // function _incompleteBeta()
  3486. /**
  3487. * BETADIST
  3488. *
  3489. * Returns the beta distribution.
  3490. *
  3491. * @param float $value Value at which you want to evaluate the distribution
  3492. * @param float $alpha Parameter to the distribution
  3493. * @param float $beta Parameter to the distribution
  3494. * @param boolean $cumulative
  3495. * @return float
  3496. *
  3497. */
  3498. public static function BETADIST($value,$alpha,$beta,$rMin=0,$rMax=1) {
  3499. $value = self::flattenSingleValue($value);
  3500. $alpha = self::flattenSingleValue($alpha);
  3501. $beta = self::flattenSingleValue($beta);
  3502. $rMin = self::flattenSingleValue($rMin);
  3503. $rMax = self::flattenSingleValue($rMax);
  3504. if ((is_numeric($value)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) {
  3505. if (($value < $rMin) || ($value > $rMax) || ($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax)) {
  3506. return self::$_errorCodes['num'];
  3507. }
  3508. if ($rMin > $rMax) {
  3509. $tmp = $rMin;
  3510. $rMin = $rMax;
  3511. $rMax = $tmp;
  3512. }
  3513. $value -= $rMin;
  3514. $value /= ($rMax - $rMin);
  3515. return self::_incompleteBeta($value,$alpha,$beta);
  3516. }
  3517. return self::$_errorCodes['value'];
  3518. } // function BETADIST()
  3519. /**
  3520. * BETAINV
  3521. *
  3522. * Returns the inverse of the beta distribution.
  3523. *
  3524. * @param float $probability Probability at which you want to evaluate the distribution
  3525. * @param float $alpha Parameter to the distribution
  3526. * @param float $beta Parameter to the distribution
  3527. * @param boolean $cumulative
  3528. * @return float
  3529. *
  3530. */
  3531. public static function BETAINV($probability,$alpha,$beta,$rMin=0,$rMax=1) {
  3532. $probability = self::flattenSingleValue($probability);
  3533. $alpha = self::flattenSingleValue($alpha);
  3534. $beta = self::flattenSingleValue($beta);
  3535. $rMin = self::flattenSingleValue($rMin);
  3536. $rMax = self::flattenSingleValue($rMax);
  3537. if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) {
  3538. if (($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax) || ($probability <= 0) || ($probability > 1)) {
  3539. return self::$_errorCodes['num'];
  3540. }
  3541. if ($rMin > $rMax) {
  3542. $tmp = $rMin;
  3543. $rMin = $rMax;
  3544. $rMax = $tmp;
  3545. }
  3546. $a = 0;
  3547. $b = 2;
  3548. $i = 0;
  3549. while ((($b - $a) > PRECISION) && ($i++ < MAX_ITERATIONS)) {
  3550. $guess = ($a + $b) / 2;
  3551. $result = self::BETADIST($guess, $alpha, $beta);
  3552. if (($result == $probability) || ($result == 0)) {
  3553. $b = $a;
  3554. } elseif ($result > $probability) {
  3555. $b = $guess;
  3556. } else {
  3557. $a = $guess;
  3558. }
  3559. }
  3560. if ($i == MAX_ITERATIONS) {
  3561. return self::$_errorCodes['na'];
  3562. }
  3563. return round($rMin + $guess * ($rMax - $rMin),12);
  3564. }
  3565. return self::$_errorCodes['value'];
  3566. } // function BETAINV()
  3567. //
  3568. // Private implementation of the incomplete Gamma function
  3569. //
  3570. private static function _incompleteGamma($a,$x) {
  3571. static $max = 32;
  3572. $summer = 0;
  3573. for ($n=0; $n<=$max; ++$n) {
  3574. $divisor = $a;
  3575. for ($i=1; $i<=$n; ++$i) {
  3576. $divisor *= ($a + $i);
  3577. }
  3578. $summer += (pow($x,$n) / $divisor);
  3579. }
  3580. return pow($x,$a) * exp(0-$x) * $summer;
  3581. } // function _incompleteGamma()
  3582. //
  3583. // Private implementation of the Gamma function
  3584. //
  3585. private static function _gamma($data) {
  3586. if ($data == 0.0) return 0;
  3587. static $p0 = 1.000000000190015;
  3588. static $p = array ( 1 => 76.18009172947146,
  3589. 2 => -86.50532032941677,
  3590. 3 => 24.01409824083091,
  3591. 4 => -1.231739572450155,
  3592. 5 => 1.208650973866179e-3,
  3593. 6 => -5.395239384953e-6
  3594. );
  3595. $y = $x = $data;
  3596. $tmp = $x + 5.5;
  3597. $tmp -= ($x + 0.5) * log($tmp);
  3598. $summer = $p0;
  3599. for ($j=1;$j<=6;++$j) {
  3600. $summer += ($p[$j] / ++$y);
  3601. }
  3602. return exp(0 - $tmp + log(SQRT2PI * $summer / $x));
  3603. } // function _gamma()
  3604. /**
  3605. * GAMMADIST
  3606. *
  3607. * Returns the gamma distribution.
  3608. *
  3609. * @param float $value Value at which you want to evaluate the distribution
  3610. * @param float $a Parameter to the distribution
  3611. * @param float $b Parameter to the distribution
  3612. * @param boolean $cumulative
  3613. * @return float
  3614. *
  3615. */
  3616. public static function GAMMADIST($value,$a,$b,$cumulative) {
  3617. $value = self::flattenSingleValue($value);
  3618. $a = self::flattenSingleValue($a);
  3619. $b = self::flattenSingleValue($b);
  3620. if ((is_numeric($value)) && (is_numeric($a)) && (is_numeric($b))) {
  3621. if (($value < 0) || ($a <= 0) || ($b <= 0)) {
  3622. return self::$_errorCodes['num'];
  3623. }
  3624. if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
  3625. if ($cumulative) {
  3626. return self::_incompleteGamma($a,$value / $b) / self::_gamma($a);
  3627. } else {
  3628. return (1 / (pow($b,$a) * self::_gamma($a))) * pow($value,$a-1) * exp(0-($value / $b));
  3629. }
  3630. }
  3631. }
  3632. return self::$_errorCodes['value'];
  3633. } // function GAMMADIST()
  3634. /**
  3635. * GAMMAINV
  3636. *
  3637. * Returns the inverse of the beta distribution.
  3638. *
  3639. * @param float $probability Probability at which you want to evaluate the distribution
  3640. * @param float $alpha Parameter to the distribution
  3641. * @param float $beta Parameter to the distribution
  3642. * @return float
  3643. *
  3644. */
  3645. public static function GAMMAINV($probability,$alpha,$beta) {
  3646. $probability = self::flattenSingleValue($probability);
  3647. $alpha = self::flattenSingleValue($alpha);
  3648. $beta = self::flattenSingleValue($beta);
  3649. if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta))) {
  3650. if (($alpha <= 0) || ($beta <= 0) || ($probability < 0) || ($probability > 1)) {
  3651. return self::$_errorCodes['num'];
  3652. }
  3653. $xLo = 0;
  3654. $xHi = $alpha * $beta * 5;
  3655. $x = $xNew = 1;
  3656. $error = $pdf = 0;
  3657. $dx = 1024;
  3658. $i = 0;
  3659. while ((abs($dx) > PRECISION) && ($i++ < MAX_ITERATIONS)) {
  3660. // Apply Newton-Raphson step
  3661. $error = self::GAMMADIST($x, $alpha, $beta, True) - $probability;
  3662. if ($error < 0.0) {
  3663. $xLo = $x;
  3664. } else {
  3665. $xHi = $x;
  3666. }
  3667. $pdf = self::GAMMADIST($x, $alpha, $beta, False);
  3668. // Avoid division by zero
  3669. if ($pdf != 0.0) {
  3670. $dx = $error / $pdf;
  3671. $xNew = $x - $dx;
  3672. }
  3673. // If the NR fails to converge (which for example may be the
  3674. // case if the initial guess is too rough) we apply a bisection
  3675. // step to determine a more narrow interval around the root.
  3676. if (($xNew < $xLo) || ($xNew > $xHi) || ($pdf == 0.0)) {
  3677. $xNew = ($xLo + $xHi) / 2;
  3678. $dx = $xNew - $x;
  3679. }
  3680. $x = $xNew;
  3681. }
  3682. if ($i == MAX_ITERATIONS) {
  3683. return self::$_errorCodes['na'];
  3684. }
  3685. return $x;
  3686. }
  3687. return self::$_errorCodes['value'];
  3688. } // function GAMMAINV()
  3689. /**
  3690. * GAMMALN
  3691. *
  3692. * Returns the natural logarithm of the gamma function.
  3693. *
  3694. * @param float $value
  3695. * @return float
  3696. */
  3697. public static function GAMMALN($value) {
  3698. $value = self::flattenSingleValue($value);
  3699. if (is_numeric($value)) {
  3700. if ($value <= 0) {
  3701. return self::$_errorCodes['num'];
  3702. }
  3703. return log(self::_gamma($value));
  3704. }
  3705. return self::$_errorCodes['value'];
  3706. } // function GAMMALN()
  3707. /**
  3708. * NORMDIST
  3709. *
  3710. * Returns the normal distribution for the specified mean and standard deviation. This
  3711. * function has a very wide range of applications in statistics, including hypothesis
  3712. * testing.
  3713. *
  3714. * @param float $value
  3715. * @param float $mean Mean Value
  3716. * @param float $stdDev Standard Deviation
  3717. * @param boolean $cumulative
  3718. * @return float
  3719. *
  3720. */
  3721. public static function NORMDIST($value, $mean, $stdDev, $cumulative) {
  3722. $value = self::flattenSingleValue($value);
  3723. $mean = self::flattenSingleValue($mean);
  3724. $stdDev = self::flattenSingleValue($stdDev);
  3725. if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
  3726. if ($stdDev < 0) {
  3727. return self::$_errorCodes['num'];
  3728. }
  3729. if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
  3730. if ($cumulative) {
  3731. return 0.5 * (1 + self::_erfVal(($value - $mean) / ($stdDev * sqrt(2))));
  3732. } else {
  3733. return (1 / (SQRT2PI * $stdDev)) * exp(0 - (pow($value - $mean,2) / (2 * ($stdDev * $stdDev))));
  3734. }
  3735. }
  3736. }
  3737. return self::$_errorCodes['value'];
  3738. } // function NORMDIST()
  3739. /**
  3740. * NORMSDIST
  3741. *
  3742. * Returns the standard normal cumulative distribution function. The distribution has
  3743. * a mean of 0 (zero) and a standard deviation of one. Use this function in place of a
  3744. * table of standard normal curve areas.
  3745. *
  3746. * @param float $value
  3747. * @return float
  3748. */
  3749. public static function NORMSDIST($value) {
  3750. $value = self::flattenSingleValue($value);
  3751. return self::NORMDIST($value, 0, 1, True);
  3752. } // function NORMSDIST()
  3753. /**
  3754. * LOGNORMDIST
  3755. *
  3756. * Returns the cumulative lognormal distribution of x, where ln(x) is normally distributed
  3757. * with parameters mean and standard_dev.
  3758. *
  3759. * @param float $value
  3760. * @return float
  3761. */
  3762. public static function LOGNORMDIST($value, $mean, $stdDev) {
  3763. $value = self::flattenSingleValue($value);
  3764. $mean = self::flattenSingleValue($mean);
  3765. $stdDev = self::flattenSingleValue($stdDev);
  3766. if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
  3767. if (($value <= 0) || ($stdDev <= 0)) {
  3768. return self::$_errorCodes['num'];
  3769. }
  3770. return self::NORMSDIST((log($value) - $mean) / $stdDev);
  3771. }
  3772. return self::$_errorCodes['value'];
  3773. } // function LOGNORMDIST()
  3774. /***************************************************************************
  3775. * inverse_ncdf.php
  3776. * -------------------
  3777. * begin : Friday, January 16, 2004
  3778. * copyright : (C) 2004 Michael Nickerson
  3779. * email : nickersonm@yahoo.com
  3780. *
  3781. ***************************************************************************/
  3782. private static function _inverse_ncdf($p) {
  3783. // Inverse ncdf approximation by Peter J. Acklam, implementation adapted to
  3784. // PHP by Michael Nickerson, using Dr. Thomas Ziegler's C implementation as
  3785. // a guide. http://home.online.no/~pjacklam/notes/invnorm/index.html
  3786. // I have not checked the accuracy of this implementation. Be aware that PHP
  3787. // will truncate the coeficcients to 14 digits.
  3788. // You have permission to use and distribute this function freely for
  3789. // whatever purpose you want, but please show common courtesy and give credit
  3790. // where credit is due.
  3791. // Input paramater is $p - probability - where 0 < p < 1.
  3792. // Coefficients in rational approximations
  3793. static $a = array( 1 => -3.969683028665376e+01,
  3794. 2 => 2.209460984245205e+02,
  3795. 3 => -2.759285104469687e+02,
  3796. 4 => 1.383577518672690e+02,
  3797. 5 => -3.066479806614716e+01,
  3798. 6 => 2.506628277459239e+00
  3799. );
  3800. static $b = array( 1 => -5.447609879822406e+01,
  3801. 2 => 1.615858368580409e+02,
  3802. 3 => -1.556989798598866e+02,
  3803. 4 => 6.680131188771972e+01,
  3804. 5 => -1.328068155288572e+01
  3805. );
  3806. static $c = array( 1 => -7.784894002430293e-03,
  3807. 2 => -3.223964580411365e-01,
  3808. 3 => -2.400758277161838e+00,
  3809. 4 => -2.549732539343734e+00,
  3810. 5 => 4.374664141464968e+00,
  3811. 6 => 2.938163982698783e+00
  3812. );
  3813. static $d = array( 1 => 7.784695709041462e-03,
  3814. 2 => 3.224671290700398e-01,
  3815. 3 => 2.445134137142996e+00,
  3816. 4 => 3.754408661907416e+00
  3817. );
  3818. // Define lower and upper region break-points.
  3819. $p_low = 0.02425; //Use lower region approx. below this
  3820. $p_high = 1 - $p_low; //Use upper region approx. above this
  3821. if (0 < $p && $p < $p_low) {
  3822. // Rational approximation for lower region.
  3823. $q = sqrt(-2 * log($p));
  3824. return ((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) /
  3825. (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1);
  3826. } elseif ($p_low <= $p && $p <= $p_high) {
  3827. // Rational approximation for central region.
  3828. $q = $p - 0.5;
  3829. $r = $q * $q;
  3830. return ((((($a[1] * $r + $a[2]) * $r + $a[3]) * $r + $a[4]) * $r + $a[5]) * $r + $a[6]) * $q /
  3831. ((((($b[1] * $r + $b[2]) * $r + $b[3]) * $r + $b[4]) * $r + $b[5]) * $r + 1);
  3832. } elseif ($p_high < $p && $p < 1) {
  3833. // Rational approximation for upper region.
  3834. $q = sqrt(-2 * log(1 - $p));
  3835. return -((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) /
  3836. (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1);
  3837. }
  3838. // If 0 < p < 1, return a null value
  3839. return self::$_errorCodes['null'];
  3840. } // function _inverse_ncdf()
  3841. private static function _inverse_ncdf2($prob) {
  3842. // Approximation of inverse standard normal CDF developed by
  3843. // B. Moro, "The Full Monte," Risk 8(2), Feb 1995, 57-58.
  3844. $a1 = 2.50662823884;
  3845. $a2 = -18.61500062529;
  3846. $a3 = 41.39119773534;
  3847. $a4 = -25.44106049637;
  3848. $b1 = -8.4735109309;
  3849. $b2 = 23.08336743743;
  3850. $b3 = -21.06224101826;
  3851. $b4 = 3.13082909833;
  3852. $c1 = 0.337475482272615;
  3853. $c2 = 0.976169019091719;
  3854. $c3 = 0.160797971491821;
  3855. $c4 = 2.76438810333863E-02;
  3856. $c5 = 3.8405729373609E-03;
  3857. $c6 = 3.951896511919E-04;
  3858. $c7 = 3.21767881768E-05;
  3859. $c8 = 2.888167364E-07;
  3860. $c9 = 3.960315187E-07;
  3861. $y = $prob - 0.5;
  3862. if (abs($y) < 0.42) {
  3863. $z = ($y * $y);
  3864. $z = $y * ((($a4 * $z + $a3) * $z + $a2) * $z + $a1) / (((($b4 * $z + $b3) * $z + $b2) * $z + $b1) * $z + 1);
  3865. } else {
  3866. if ($y > 0) {
  3867. $z = log(-log(1 - $prob));
  3868. } else {
  3869. $z = log(-log($prob));
  3870. }
  3871. $z = $c1 + $z * ($c2 + $z * ($c3 + $z * ($c4 + $z * ($c5 + $z * ($c6 + $z * ($c7 + $z * ($c8 + $z * $c9)))))));
  3872. if ($y < 0) {
  3873. $z = -$z;
  3874. }
  3875. }
  3876. return $z;
  3877. } // function _inverse_ncdf2()
  3878. private static function _inverse_ncdf3($p) {
  3879. // ALGORITHM AS241 APPL. STATIST. (1988) VOL. 37, NO. 3.
  3880. // Produces the normal deviate Z corresponding to a given lower
  3881. // tail area of P; Z is accurate to about 1 part in 10**16.
  3882. //
  3883. // This is a PHP version of the original FORTRAN code that can
  3884. // be found at http://lib.stat.cmu.edu/apstat/
  3885. $split1 = 0.425;
  3886. $split2 = 5;
  3887. $const1 = 0.180625;
  3888. $const2 = 1.6;
  3889. // coefficients for p close to 0.5
  3890. $a0 = 3.3871328727963666080;
  3891. $a1 = 1.3314166789178437745E+2;
  3892. $a2 = 1.9715909503065514427E+3;
  3893. $a3 = 1.3731693765509461125E+4;
  3894. $a4 = 4.5921953931549871457E+4;
  3895. $a5 = 6.7265770927008700853E+4;
  3896. $a6 = 3.3430575583588128105E+4;
  3897. $a7 = 2.5090809287301226727E+3;
  3898. $b1 = 4.2313330701600911252E+1;
  3899. $b2 = 6.8718700749205790830E+2;
  3900. $b3 = 5.3941960214247511077E+3;
  3901. $b4 = 2.1213794301586595867E+4;
  3902. $b5 = 3.9307895800092710610E+4;
  3903. $b6 = 2.8729085735721942674E+4;
  3904. $b7 = 5.2264952788528545610E+3;
  3905. // coefficients for p not close to 0, 0.5 or 1.
  3906. $c0 = 1.42343711074968357734;
  3907. $c1 = 4.63033784615654529590;
  3908. $c2 = 5.76949722146069140550;
  3909. $c3 = 3.64784832476320460504;
  3910. $c4 = 1.27045825245236838258;
  3911. $c5 = 2.41780725177450611770E-1;
  3912. $c6 = 2.27238449892691845833E-2;
  3913. $c7 = 7.74545014278341407640E-4;
  3914. $d1 = 2.05319162663775882187;
  3915. $d2 = 1.67638483018380384940;
  3916. $d3 = 6.89767334985100004550E-1;
  3917. $d4 = 1.48103976427480074590E-1;
  3918. $d5 = 1.51986665636164571966E-2;
  3919. $d6 = 5.47593808499534494600E-4;
  3920. $d7 = 1.05075007164441684324E-9;
  3921. // coefficients for p near 0 or 1.
  3922. $e0 = 6.65790464350110377720;
  3923. $e1 = 5.46378491116411436990;
  3924. $e2 = 1.78482653991729133580;
  3925. $e3 = 2.96560571828504891230E-1;
  3926. $e4 = 2.65321895265761230930E-2;
  3927. $e5 = 1.24266094738807843860E-3;
  3928. $e6 = 2.71155556874348757815E-5;
  3929. $e7 = 2.01033439929228813265E-7;
  3930. $f1 = 5.99832206555887937690E-1;
  3931. $f2 = 1.36929880922735805310E-1;
  3932. $f3 = 1.48753612908506148525E-2;
  3933. $f4 = 7.86869131145613259100E-4;
  3934. $f5 = 1.84631831751005468180E-5;
  3935. $f6 = 1.42151175831644588870E-7;
  3936. $f7 = 2.04426310338993978564E-15;
  3937. $q = $p - 0.5;
  3938. // computation for p close to 0.5
  3939. if (abs($q) <= split1) {
  3940. $R = $const1 - $q * $q;
  3941. $z = $q * ((((((($a7 * $R + $a6) * $R + $a5) * $R + $a4) * $R + $a3) * $R + $a2) * $R + $a1) * $R + $a0) /
  3942. ((((((($b7 * $R + $b6) * $R + $b5) * $R + $b4) * $R + $b3) * $R + $b2) * $R + $b1) * $R + 1);
  3943. } else {
  3944. if ($q < 0) {
  3945. $R = $p;
  3946. } else {
  3947. $R = 1 - $p;
  3948. }
  3949. $R = pow(-log($R),2);
  3950. // computation for p not close to 0, 0.5 or 1.
  3951. If ($R <= $split2) {
  3952. $R = $R - $const2;
  3953. $z = ((((((($c7 * $R + $c6) * $R + $c5) * $R + $c4) * $R + $c3) * $R + $c2) * $R + $c1) * $R + $c0) /
  3954. ((((((($d7 * $R + $d6) * $R + $d5) * $R + $d4) * $R + $d3) * $R + $d2) * $R + $d1) * $R + 1);
  3955. } else {
  3956. // computation for p near 0 or 1.
  3957. $R = $R - $split2;
  3958. $z = ((((((($e7 * $R + $e6) * $R + $e5) * $R + $e4) * $R + $e3) * $R + $e2) * $R + $e1) * $R + $e0) /
  3959. ((((((($f7 * $R + $f6) * $R + $f5) * $R + $f4) * $R + $f3) * $R + $f2) * $R + $f1) * $R + 1);
  3960. }
  3961. if ($q < 0) {
  3962. $z = -$z;
  3963. }
  3964. }
  3965. return $z;
  3966. } // function _inverse_ncdf3()
  3967. /**
  3968. * NORMINV
  3969. *
  3970. * Returns the inverse of the normal cumulative distribution for the specified mean and standard deviation.
  3971. *
  3972. * @param float $value
  3973. * @param float $mean Mean Value
  3974. * @param float $stdDev Standard Deviation
  3975. * @return float
  3976. *
  3977. */
  3978. public static function NORMINV($probability,$mean,$stdDev) {
  3979. $probability = self::flattenSingleValue($probability);
  3980. $mean = self::flattenSingleValue($mean);
  3981. $stdDev = self::flattenSingleValue($stdDev);
  3982. if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
  3983. if (($probability < 0) || ($probability > 1)) {
  3984. return self::$_errorCodes['num'];
  3985. }
  3986. if ($stdDev < 0) {
  3987. return self::$_errorCodes['num'];
  3988. }
  3989. return (self::_inverse_ncdf($probability) * $stdDev) + $mean;
  3990. }
  3991. return self::$_errorCodes['value'];
  3992. } // function NORMINV()
  3993. /**
  3994. * NORMSINV
  3995. *
  3996. * Returns the inverse of the standard normal cumulative distribution
  3997. *
  3998. * @param float $value
  3999. * @return float
  4000. */
  4001. public static function NORMSINV($value) {
  4002. return self::NORMINV($value, 0, 1);
  4003. } // function NORMSINV()
  4004. /**
  4005. * LOGINV
  4006. *
  4007. * Returns the inverse of the normal cumulative distribution
  4008. *
  4009. * @param float $value
  4010. * @return float
  4011. *
  4012. * @todo Try implementing P J Acklam's refinement algorithm for greater
  4013. * accuracy if I can get my head round the mathematics
  4014. * (as described at) http://home.online.no/~pjacklam/notes/invnorm/
  4015. */
  4016. public static function LOGINV($probability, $mean, $stdDev) {
  4017. $probability = self::flattenSingleValue($probability);
  4018. $mean = self::flattenSingleValue($mean);
  4019. $stdDev = self::flattenSingleValue($stdDev);
  4020. if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
  4021. if (($probability < 0) || ($probability > 1) || ($stdDev <= 0)) {
  4022. return self::$_errorCodes['num'];
  4023. }
  4024. return exp($mean + $stdDev * self::NORMSINV($probability));
  4025. }
  4026. return self::$_errorCodes['value'];
  4027. } // function LOGINV()
  4028. /**
  4029. * HYPGEOMDIST
  4030. *
  4031. * Returns the hypergeometric distribution. HYPGEOMDIST returns the probability of a given number of
  4032. * sample successes, given the sample size, population successes, and population size.
  4033. *
  4034. * @param float $sampleSuccesses Number of successes in the sample
  4035. * @param float $sampleNumber Size of the sample
  4036. * @param float $populationSuccesses Number of successes in the population
  4037. * @param float $populationNumber Population size
  4038. * @return float
  4039. *
  4040. */
  4041. public static function HYPGEOMDIST($sampleSuccesses, $sampleNumber, $populationSuccesses, $populationNumber) {
  4042. $sampleSuccesses = floor(self::flattenSingleValue($sampleSuccesses));
  4043. $sampleNumber = floor(self::flattenSingleValue($sampleNumber));
  4044. $populationSuccesses = floor(self::flattenSingleValue($populationSuccesses));
  4045. $populationNumber = floor(self::flattenSingleValue($populationNumber));
  4046. if ((is_numeric($sampleSuccesses)) && (is_numeric($sampleNumber)) && (is_numeric($populationSuccesses)) && (is_numeric($populationNumber))) {
  4047. if (($sampleSuccesses < 0) || ($sampleSuccesses > $sampleNumber) || ($sampleSuccesses > $populationSuccesses)) {
  4048. return self::$_errorCodes['num'];
  4049. }
  4050. if (($sampleNumber <= 0) || ($sampleNumber > $populationNumber)) {
  4051. return self::$_errorCodes['num'];
  4052. }
  4053. if (($populationSuccesses <= 0) || ($populationSuccesses > $populationNumber)) {
  4054. return self::$_errorCodes['num'];
  4055. }
  4056. return self::COMBIN($populationSuccesses,$sampleSuccesses) *
  4057. self::COMBIN($populationNumber - $populationSuccesses,$sampleNumber - $sampleSuccesses) /
  4058. self::COMBIN($populationNumber,$sampleNumber);
  4059. }
  4060. return self::$_errorCodes['value'];
  4061. } // function HYPGEOMDIST()
  4062. /**
  4063. * TDIST
  4064. *
  4065. * Returns the probability of Student's T distribution.
  4066. *
  4067. * @param float $value Value for the function
  4068. * @param float $degrees degrees of freedom
  4069. * @param float $tails number of tails (1 or 2)
  4070. * @return float
  4071. */
  4072. public static function TDIST($value, $degrees, $tails) {
  4073. $value = self::flattenSingleValue($value);
  4074. $degrees = floor(self::flattenSingleValue($degrees));
  4075. $tails = floor(self::flattenSingleValue($tails));
  4076. if ((is_numeric($value)) && (is_numeric($degrees)) && (is_numeric($tails))) {
  4077. if (($value < 0) || ($degrees < 1) || ($tails < 1) || ($tails > 2)) {
  4078. return self::$_errorCodes['num'];
  4079. }
  4080. // tdist, which finds the probability that corresponds to a given value
  4081. // of t with k degrees of freedom. This algorithm is translated from a
  4082. // pascal function on p81 of "Statistical Computing in Pascal" by D
  4083. // Cooke, A H Craven & G M Clark (1985: Edward Arnold (Pubs.) Ltd:
  4084. // London). The above Pascal algorithm is itself a translation of the
  4085. // fortran algoritm "AS 3" by B E Cooper of the Atlas Computer
  4086. // Laboratory as reported in (among other places) "Applied Statistics
  4087. // Algorithms", editied by P Griffiths and I D Hill (1985; Ellis
  4088. // Horwood Ltd.; W. Sussex, England).
  4089. $tterm = $degrees;
  4090. $ttheta = atan2($value,sqrt($tterm));
  4091. $tc = cos($ttheta);
  4092. $ts = sin($ttheta);
  4093. $tsum = 0;
  4094. if (($degrees % 2) == 1) {
  4095. $ti = 3;
  4096. $tterm = $tc;
  4097. } else {
  4098. $ti = 2;
  4099. $tterm = 1;
  4100. }
  4101. $tsum = $tterm;
  4102. while ($ti < $degrees) {
  4103. $tterm *= $tc * $tc * ($ti - 1) / $ti;
  4104. $tsum += $tterm;
  4105. $ti += 2;
  4106. }
  4107. $tsum *= $ts;
  4108. if (($degrees % 2) == 1) { $tsum = M_2DIVPI * ($tsum + $ttheta); }
  4109. $tValue = 0.5 * (1 + $tsum);
  4110. if ($tails == 1) {
  4111. return 1 - abs($tValue);
  4112. } else {
  4113. return 1 - abs((1 - $tValue) - $tValue);
  4114. }
  4115. }
  4116. return self::$_errorCodes['value'];
  4117. } // function TDIST()
  4118. /**
  4119. * TINV
  4120. *
  4121. * Returns the one-tailed probability of the chi-squared distribution.
  4122. *
  4123. * @param float $probability Probability for the function
  4124. * @param float $degrees degrees of freedom
  4125. * @return float
  4126. */
  4127. public static function TINV($probability, $degrees) {
  4128. $probability = self::flattenSingleValue($probability);
  4129. $degrees = floor(self::flattenSingleValue($degrees));
  4130. if ((is_numeric($probability)) && (is_numeric($degrees))) {
  4131. $xLo = 100;
  4132. $xHi = 0;
  4133. $x = $xNew = 1;
  4134. $dx = 1;
  4135. $i = 0;
  4136. while ((abs($dx) > PRECISION) && ($i++ < MAX_ITERATIONS)) {
  4137. // Apply Newton-Raphson step
  4138. $result = self::TDIST($x, $degrees, 2);
  4139. $error = $result - $probability;
  4140. if ($error == 0.0) {
  4141. $dx = 0;
  4142. } elseif ($error < 0.0) {
  4143. $xLo = $x;
  4144. } else {
  4145. $xHi = $x;
  4146. }
  4147. // Avoid division by zero
  4148. if ($result != 0.0) {
  4149. $dx = $error / $result;
  4150. $xNew = $x - $dx;
  4151. }
  4152. // If the NR fails to converge (which for example may be the
  4153. // case if the initial guess is too rough) we apply a bisection
  4154. // step to determine a more narrow interval around the root.
  4155. if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) {
  4156. $xNew = ($xLo + $xHi) / 2;
  4157. $dx = $xNew - $x;
  4158. }
  4159. $x = $xNew;
  4160. }
  4161. if ($i == MAX_ITERATIONS) {
  4162. return self::$_errorCodes['na'];
  4163. }
  4164. return round($x,12);
  4165. }
  4166. return self::$_errorCodes['value'];
  4167. } // function TINV()
  4168. /**
  4169. * CONFIDENCE
  4170. *
  4171. * Returns the confidence interval for a population mean
  4172. *
  4173. * @param float $alpha
  4174. * @param float $stdDev Standard Deviation
  4175. * @param float $size
  4176. * @return float
  4177. *
  4178. */
  4179. public static function CONFIDENCE($alpha,$stdDev,$size) {
  4180. $alpha = self::flattenSingleValue($alpha);
  4181. $stdDev = self::flattenSingleValue($stdDev);
  4182. $size = floor(self::flattenSingleValue($size));
  4183. if ((is_numeric($alpha)) && (is_numeric($stdDev)) && (is_numeric($size))) {
  4184. if (($alpha <= 0) || ($alpha >= 1)) {
  4185. return self::$_errorCodes['num'];
  4186. }
  4187. if (($stdDev <= 0) || ($size < 1)) {
  4188. return self::$_errorCodes['num'];
  4189. }
  4190. return self::NORMSINV(1 - $alpha / 2) * $stdDev / sqrt($size);
  4191. }
  4192. return self::$_errorCodes['value'];
  4193. } // function CONFIDENCE()
  4194. /**
  4195. * POISSON
  4196. *
  4197. * Returns the Poisson distribution. A common application of the Poisson distribution
  4198. * is predicting the number of events over a specific time, such as the number of
  4199. * cars arriving at a toll plaza in 1 minute.
  4200. *
  4201. * @param float $value
  4202. * @param float $mean Mean Value
  4203. * @param boolean $cumulative
  4204. * @return float
  4205. *
  4206. */
  4207. public static function POISSON($value, $mean, $cumulative) {
  4208. $value = self::flattenSingleValue($value);
  4209. $mean = self::flattenSingleValue($mean);
  4210. if ((is_numeric($value)) && (is_numeric($mean))) {
  4211. if (($value <= 0) || ($mean <= 0)) {
  4212. return self::$_errorCodes['num'];
  4213. }
  4214. if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
  4215. if ($cumulative) {
  4216. $summer = 0;
  4217. for ($i = 0; $i <= floor($value); ++$i) {
  4218. $summer += pow($mean,$i) / self::FACT($i);
  4219. }
  4220. return exp(0-$mean) * $summer;
  4221. } else {
  4222. return (exp(0-$mean) * pow($mean,$value)) / self::FACT($value);
  4223. }
  4224. }
  4225. }
  4226. return self::$_errorCodes['value'];
  4227. } // function POISSON()
  4228. /**
  4229. * WEIBULL
  4230. *
  4231. * Returns the Weibull distribution. Use this distribution in reliability
  4232. * analysis, such as calculating a device's mean time to failure.
  4233. *
  4234. * @param float $value
  4235. * @param float $alpha Alpha Parameter
  4236. * @param float $beta Beta Parameter
  4237. * @param boolean $cumulative
  4238. * @return float
  4239. *
  4240. */
  4241. public static function WEIBULL($value, $alpha, $beta, $cumulative) {
  4242. $value = self::flattenSingleValue($value);
  4243. $alpha = self::flattenSingleValue($alpha);
  4244. $beta = self::flattenSingleValue($beta);
  4245. if ((is_numeric($value)) && (is_numeric($alpha)) && (is_numeric($beta))) {
  4246. if (($value < 0) || ($alpha <= 0) || ($beta <= 0)) {
  4247. return self::$_errorCodes['num'];
  4248. }
  4249. if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
  4250. if ($cumulative) {
  4251. return 1 - exp(0 - pow($value / $beta,$alpha));
  4252. } else {
  4253. return ($alpha / pow($beta,$alpha)) * pow($value,$alpha - 1) * exp(0 - pow($value / $beta,$alpha));
  4254. }
  4255. }
  4256. }
  4257. return self::$_errorCodes['value'];
  4258. } // function WEIBULL()
  4259. /**
  4260. * ZTEST
  4261. *
  4262. * Returns the Weibull distribution. Use this distribution in reliability
  4263. * analysis, such as calculating a device's mean time to failure.
  4264. *
  4265. * @param float $value
  4266. * @param float $alpha Alpha Parameter
  4267. * @param float $beta Beta Parameter
  4268. * @param boolean $cumulative
  4269. * @return float
  4270. *
  4271. */
  4272. public static function ZTEST($dataSet, $m0, $sigma=null) {
  4273. $dataSet = self::flattenArrayIndexed($dataSet);
  4274. $m0 = self::flattenSingleValue($m0);
  4275. $sigma = self::flattenSingleValue($sigma);
  4276. if (is_null($sigma)) {
  4277. $sigma = self::STDEV($dataSet);
  4278. }
  4279. $n = count($dataSet);
  4280. return 1 - self::NORMSDIST((self::AVERAGE($dataSet) - $m0)/($sigma/SQRT($n)));
  4281. } // function ZTEST()
  4282. /**
  4283. * SKEW
  4284. *
  4285. * Returns the skewness of a distribution. Skewness characterizes the degree of asymmetry
  4286. * of a distribution around its mean. Positive skewness indicates a distribution with an
  4287. * asymmetric tail extending toward more positive values. Negative skewness indicates a
  4288. * distribution with an asymmetric tail extending toward more negative values.
  4289. *
  4290. * @param array Data Series
  4291. * @return float
  4292. */
  4293. public static function SKEW() {
  4294. $aArgs = self::flattenArrayIndexed(func_get_args());
  4295. $mean = self::AVERAGE($aArgs);
  4296. $stdDev = self::STDEV($aArgs);
  4297. $count = $summer = 0;
  4298. // Loop through arguments
  4299. foreach ($aArgs as $k => $arg) {
  4300. if ((is_bool($arg)) &&
  4301. (!self::isMatrixValue($k))) {
  4302. } else {
  4303. // Is it a numeric value?
  4304. if ((is_numeric($arg)) && (!is_string($arg))) {
  4305. $summer += pow((($arg - $mean) / $stdDev),3) ;
  4306. ++$count;
  4307. }
  4308. }
  4309. }
  4310. // Return
  4311. if ($count > 2) {
  4312. return $summer * ($count / (($count-1) * ($count-2)));
  4313. }
  4314. return self::$_errorCodes['divisionbyzero'];
  4315. } // function SKEW()
  4316. /**
  4317. * KURT
  4318. *
  4319. * Returns the kurtosis of a data set. Kurtosis characterizes the relative peakedness
  4320. * or flatness of a distribution compared with the normal distribution. Positive
  4321. * kurtosis indicates a relatively peaked distribution. Negative kurtosis indicates a
  4322. * relatively flat distribution.
  4323. *
  4324. * @param array Data Series
  4325. * @return float
  4326. */
  4327. public static function KURT() {
  4328. $aArgs = self::flattenArrayIndexed(func_get_args());
  4329. $mean = self::AVERAGE($aArgs);
  4330. $stdDev = self::STDEV($aArgs);
  4331. if ($stdDev > 0) {
  4332. $count = $summer = 0;
  4333. // Loop through arguments
  4334. foreach ($aArgs as $k => $arg) {
  4335. if ((is_bool($arg)) &&
  4336. (!self::isMatrixValue($k))) {
  4337. } else {
  4338. // Is it a numeric value?
  4339. if ((is_numeric($arg)) && (!is_string($arg))) {
  4340. $summer += pow((($arg - $mean) / $stdDev),4) ;
  4341. ++$count;
  4342. }
  4343. }
  4344. }
  4345. // Return
  4346. if ($count > 3) {
  4347. return $summer * ($count * ($count+1) / (($count-1) * ($count-2) * ($count-3))) - (3 * pow($count-1,2) / (($count-2) * ($count-3)));
  4348. }
  4349. }
  4350. return self::$_errorCodes['divisionbyzero'];
  4351. } // function KURT()
  4352. /**
  4353. * RAND
  4354. *
  4355. * @param int $min Minimal value
  4356. * @param int $max Maximal value
  4357. * @return int Random number
  4358. */
  4359. public static function RAND($min = 0, $max = 0) {
  4360. $min = self::flattenSingleValue($min);
  4361. $max = self::flattenSingleValue($max);
  4362. if ($min == 0 && $max == 0) {
  4363. return (rand(0,10000000)) / 10000000;
  4364. } else {
  4365. return rand($min, $max);
  4366. }
  4367. } // function RAND()
  4368. /**
  4369. * MOD
  4370. *
  4371. * @param int $a Dividend
  4372. * @param int $b Divisor
  4373. * @return int Remainder
  4374. */
  4375. public static function MOD($a = 1, $b = 1) {
  4376. $a = self::flattenSingleValue($a);
  4377. $b = self::flattenSingleValue($b);
  4378. if ($b == 0.0) {
  4379. return self::$_errorCodes['divisionbyzero'];
  4380. } elseif (($a < 0.0) && ($b > 0.0)) {
  4381. return $b - fmod(abs($a),$b);
  4382. } elseif (($a > 0.0) && ($b < 0.0)) {
  4383. return $b + fmod($a,abs($b));
  4384. }
  4385. return fmod($a,$b);
  4386. } // function MOD()
  4387. /**
  4388. * CHARACTER
  4389. *
  4390. * @param string $character Value
  4391. * @return int
  4392. */
  4393. public static function CHARACTER($character) {
  4394. $character = self::flattenSingleValue($character);
  4395. if ((!is_numeric($character)) || ($character < 0)) {
  4396. return self::$_errorCodes['value'];
  4397. }
  4398. if (function_exists('mb_convert_encoding')) {
  4399. return mb_convert_encoding('&#'.intval($character).';', 'UTF-8', 'HTML-ENTITIES');
  4400. } else {
  4401. return chr(intval($character));
  4402. }
  4403. }
  4404. private static function _uniord($c) {
  4405. if (ord($c{0}) >=0 && ord($c{0}) <= 127)
  4406. return ord($c{0});
  4407. if (ord($c{0}) >= 192 && ord($c{0}) <= 223)
  4408. return (ord($c{0})-192)*64 + (ord($c{1})-128);
  4409. if (ord($c{0}) >= 224 && ord($c{0}) <= 239)
  4410. return (ord($c{0})-224)*4096 + (ord($c{1})-128)*64 + (ord($c{2})-128);
  4411. if (ord($c{0}) >= 240 && ord($c{0}) <= 247)
  4412. return (ord($c{0})-240)*262144 + (ord($c{1})-128)*4096 + (ord($c{2})-128)*64 + (ord($c{3})-128);
  4413. if (ord($c{0}) >= 248 && ord($c{0}) <= 251)
  4414. return (ord($c{0})-248)*16777216 + (ord($c{1})-128)*262144 + (ord($c{2})-128)*4096 + (ord($c{3})-128)*64 + (ord($c{4})-128);
  4415. if (ord($c{0}) >= 252 && ord($c{0}) <= 253)
  4416. return (ord($c{0})-252)*1073741824 + (ord($c{1})-128)*16777216 + (ord($c{2})-128)*262144 + (ord($c{3})-128)*4096 + (ord($c{4})-128)*64 + (ord($c{5})-128);
  4417. if (ord($c{0}) >= 254 && ord($c{0}) <= 255) //error
  4418. return self::$_errorCodes['value'];
  4419. return 0;
  4420. } // function _uniord()
  4421. /**
  4422. * ASCIICODE
  4423. *
  4424. * @param string $character Value
  4425. * @return int
  4426. */
  4427. public static function ASCIICODE($characters) {
  4428. $characters = self::flattenSingleValue($characters);
  4429. if (is_bool($characters)) {
  4430. if (self::$compatibilityMode == self::COMPATIBILITY_OPENOFFICE) {
  4431. $characters = (int) $characters;
  4432. } else {
  4433. if ($characters) {
  4434. $characters = 'True';
  4435. } else {
  4436. $characters = 'False';
  4437. }
  4438. }
  4439. }
  4440. $character = $characters;
  4441. if ((function_exists('mb_strlen')) && (function_exists('mb_substr'))) {
  4442. if (mb_strlen($characters, 'UTF-8') > 1) { $character = mb_substr($characters, 0, 1, 'UTF-8'); }
  4443. return self::_uniord($character);
  4444. } else {
  4445. if (strlen($characters) > 0) { $character = substr($characters, 0, 1); }
  4446. return ord($character);
  4447. }
  4448. } // function ASCIICODE()
  4449. /**
  4450. * CONCATENATE
  4451. *
  4452. * @return string
  4453. */
  4454. public static function CONCATENATE() {
  4455. // Return value
  4456. $returnValue = '';
  4457. // Loop through arguments
  4458. $aArgs = self::flattenArray(func_get_args());
  4459. foreach ($aArgs as $arg) {
  4460. if (is_bool($arg)) {
  4461. if (self::$compatibilityMode == self::COMPATIBILITY_OPENOFFICE) {
  4462. $arg = (int) $arg;
  4463. } else {
  4464. if ($arg) {
  4465. $arg = 'TRUE';
  4466. } else {
  4467. $arg = 'FALSE';
  4468. }
  4469. }
  4470. }
  4471. $returnValue .= $arg;
  4472. }
  4473. // Return
  4474. return $returnValue;
  4475. } // function CONCATENATE()
  4476. /**
  4477. * STRINGLENGTH
  4478. *
  4479. * @param string $value Value
  4480. * @param int $chars Number of characters
  4481. * @return string
  4482. */
  4483. public static function STRINGLENGTH($value = '') {
  4484. $value = self::flattenSingleValue($value);
  4485. if (is_bool($value)) {
  4486. $value = ($value) ? 'TRUE' : 'FALSE';
  4487. }
  4488. if (function_exists('mb_strlen')) {
  4489. return mb_strlen($value, 'UTF-8');
  4490. } else {
  4491. return strlen($value);
  4492. }
  4493. } // function STRINGLENGTH()
  4494. /**
  4495. * SEARCHSENSITIVE
  4496. *
  4497. * @param string $needle The string to look for
  4498. * @param string $haystack The string in which to look
  4499. * @param int $offset Offset within $haystack
  4500. * @return string
  4501. */
  4502. public static function SEARCHSENSITIVE($needle,$haystack,$offset=1) {
  4503. $needle = self::flattenSingleValue($needle);
  4504. $haystack = self::flattenSingleValue($haystack);
  4505. $offset = self::flattenSingleValue($offset);
  4506. if (!is_bool($needle)) {
  4507. if (is_bool($haystack)) {
  4508. $haystack = ($haystack) ? 'TRUE' : 'FALSE';
  4509. }
  4510. if (($offset > 0) && (strlen($haystack) > $offset)) {
  4511. if (function_exists('mb_strpos')) {
  4512. $pos = mb_strpos($haystack, $needle, --$offset,'UTF-8');
  4513. } else {
  4514. $pos = strpos($haystack, $needle, --$offset);
  4515. }
  4516. if ($pos !== false) {
  4517. return ++$pos;
  4518. }
  4519. }
  4520. }
  4521. return self::$_errorCodes['value'];
  4522. } // function SEARCHSENSITIVE()
  4523. /**
  4524. * SEARCHINSENSITIVE
  4525. *
  4526. * @param string $needle The string to look for
  4527. * @param string $haystack The string in which to look
  4528. * @param int $offset Offset within $haystack
  4529. * @return string
  4530. */
  4531. public static function SEARCHINSENSITIVE($needle,$haystack,$offset=1) {
  4532. $needle = self::flattenSingleValue($needle);
  4533. $haystack = self::flattenSingleValue($haystack);
  4534. $offset = self::flattenSingleValue($offset);
  4535. if (!is_bool($needle)) {
  4536. if (is_bool($haystack)) {
  4537. $haystack = ($haystack) ? 'TRUE' : 'FALSE';
  4538. }
  4539. if (($offset > 0) && (strlen($haystack) > $offset)) {
  4540. if (function_exists('mb_stripos')) {
  4541. $pos = mb_stripos($haystack, $needle, --$offset,'UTF-8');
  4542. } else {
  4543. $pos = stripos($haystack, $needle, --$offset);
  4544. }
  4545. if ($pos !== false) {
  4546. return ++$pos;
  4547. }
  4548. }
  4549. }
  4550. return self::$_errorCodes['value'];
  4551. } // function SEARCHINSENSITIVE()
  4552. /**
  4553. * LEFT
  4554. *
  4555. * @param string $value Value
  4556. * @param int $chars Number of characters
  4557. * @return string
  4558. */
  4559. public static function LEFT($value = '', $chars = 1) {
  4560. $value = self::flattenSingleValue($value);
  4561. $chars = self::flattenSingleValue($chars);
  4562. if ($chars < 0) {
  4563. return self::$_errorCodes['value'];
  4564. }
  4565. if (is_bool($value)) {
  4566. $value = ($value) ? 'TRUE' : 'FALSE';
  4567. }
  4568. if (function_exists('mb_substr')) {
  4569. return mb_substr($value, 0, $chars, 'UTF-8');
  4570. } else {
  4571. return substr($value, 0, $chars);
  4572. }
  4573. } // function LEFT()
  4574. /**
  4575. * RIGHT
  4576. *
  4577. * @param string $value Value
  4578. * @param int $chars Number of characters
  4579. * @return string
  4580. */
  4581. public static function RIGHT($value = '', $chars = 1) {
  4582. $value = self::flattenSingleValue($value);
  4583. $chars = self::flattenSingleValue($chars);
  4584. if ($chars < 0) {
  4585. return self::$_errorCodes['value'];
  4586. }
  4587. if (is_bool($value)) {
  4588. $value = ($value) ? 'TRUE' : 'FALSE';
  4589. }
  4590. if ((function_exists('mb_substr')) && (function_exists('mb_strlen'))) {
  4591. return mb_substr($value, mb_strlen($value, 'UTF-8') - $chars, $chars, 'UTF-8');
  4592. } else {
  4593. return substr($value, strlen($value) - $chars);
  4594. }
  4595. } // function RIGHT()
  4596. /**
  4597. * MID
  4598. *
  4599. * @param string $value Value
  4600. * @param int $start Start character
  4601. * @param int $chars Number of characters
  4602. * @return string
  4603. */
  4604. public static function MID($value = '', $start = 1, $chars = null) {
  4605. $value = self::flattenSingleValue($value);
  4606. $start = self::flattenSingleValue($start);
  4607. $chars = self::flattenSingleValue($chars);
  4608. if (($start < 1) || ($chars < 0)) {
  4609. return self::$_errorCodes['value'];
  4610. }
  4611. if (is_bool($value)) {
  4612. $value = ($value) ? 'TRUE' : 'FALSE';
  4613. }
  4614. if (function_exists('mb_substr')) {
  4615. return mb_substr($value, --$start, $chars, 'UTF-8');
  4616. } else {
  4617. return substr($value, --$start, $chars);
  4618. }
  4619. } // function MID()
  4620. /**
  4621. * REPLACE
  4622. *
  4623. * @param string $value Value
  4624. * @param int $start Start character
  4625. * @param int $chars Number of characters
  4626. * @return string
  4627. */
  4628. public static function REPLACE($oldText = '', $start = 1, $chars = null, $newText) {
  4629. $oldText = self::flattenSingleValue($oldText);
  4630. $start = self::flattenSingleValue($start);
  4631. $chars = self::flattenSingleValue($chars);
  4632. $newText = self::flattenSingleValue($newText);
  4633. $left = self::LEFT($oldText,$start-1);
  4634. $right = self::RIGHT($oldText,self::STRINGLENGTH($oldText)-($start+$chars)+1);
  4635. return $left.$newText.$right;
  4636. } // function REPLACE()
  4637. /**
  4638. * SUBSTITUTE
  4639. *
  4640. * @param string $text Value
  4641. * @param string $fromText From Value
  4642. * @param string $toText To Value
  4643. * @param integer $instance Instance Number
  4644. * @return string
  4645. */
  4646. public static function SUBSTITUTE($text = '', $fromText = '', $toText = '', $instance = 0) {
  4647. $text = self::flattenSingleValue($text);
  4648. $fromText = self::flattenSingleValue($fromText);
  4649. $toText = self::flattenSingleValue($toText);
  4650. $instance = floor(self::flattenSingleValue($instance));
  4651. if ($instance == 0) {
  4652. if(function_exists('mb_str_replace')) {
  4653. return mb_str_replace($fromText,$toText,$text);
  4654. } else {
  4655. return str_replace($fromText,$toText,$text);
  4656. }
  4657. } else {
  4658. $pos = -1;
  4659. while($instance > 0) {
  4660. if (function_exists('mb_strpos')) {
  4661. $pos = mb_strpos($text, $fromText, $pos+1, 'UTF-8');
  4662. } else {
  4663. $pos = strpos($text, $fromText, $pos+1);
  4664. }
  4665. if ($pos === false) {
  4666. break;
  4667. }
  4668. --$instance;
  4669. }
  4670. if ($pos !== false) {
  4671. if (function_exists('mb_strlen')) {
  4672. return self::REPLACE($text,++$pos,mb_strlen($fromText, 'UTF-8'),$toText);
  4673. } else {
  4674. return self::REPLACE($text,++$pos,strlen($fromText),$toText);
  4675. }
  4676. }
  4677. }
  4678. return $left.$newText.$right;
  4679. } // function SUBSTITUTE()
  4680. /**
  4681. * RETURNSTRING
  4682. *
  4683. * @param mixed $value Value to check
  4684. * @return boolean
  4685. */
  4686. public static function RETURNSTRING($testValue = '') {
  4687. $testValue = self::flattenSingleValue($testValue);
  4688. if (is_string($testValue)) {
  4689. return $testValue;
  4690. }
  4691. return Null;
  4692. } // function RETURNSTRING()
  4693. /**
  4694. * FIXEDFORMAT
  4695. *
  4696. * @param mixed $value Value to check
  4697. * @return boolean
  4698. */
  4699. public static function FIXEDFORMAT($value,$decimals=2,$no_commas=false) {
  4700. $value = self::flattenSingleValue($value);
  4701. $decimals = self::flattenSingleValue($decimals);
  4702. $no_commas = self::flattenSingleValue($no_commas);
  4703. $valueResult = round($value,$decimals);
  4704. if ($decimals < 0) { $decimals = 0; }
  4705. if (!$no_commas) {
  4706. $valueResult = number_format($valueResult,$decimals);
  4707. }
  4708. return (string) $valueResult;
  4709. } // function FIXEDFORMAT()
  4710. /**
  4711. * TEXTFORMAT
  4712. *
  4713. * @param mixed $value Value to check
  4714. * @return boolean
  4715. */
  4716. public static function TEXTFORMAT($value,$format) {
  4717. $value = self::flattenSingleValue($value);
  4718. $format = self::flattenSingleValue($format);
  4719. if ((is_string($value)) && (!is_numeric($value)) && PHPExcel_Shared_Date::isDateTimeFormatCode($format)) {
  4720. $value = self::DATEVALUE($value);
  4721. }
  4722. return (string) PHPExcel_Style_NumberFormat::toFormattedString($value,$format);
  4723. } // function TEXTFORMAT()
  4724. /**
  4725. * TRIMSPACES
  4726. *
  4727. * @param mixed $value Value to check
  4728. * @return string
  4729. */
  4730. public static function TRIMSPACES($stringValue = '') {
  4731. $stringValue = self::flattenSingleValue($stringValue);
  4732. if (is_string($stringValue) || is_numeric($stringValue)) {
  4733. return trim(preg_replace('/ +/',' ',$stringValue));
  4734. }
  4735. return Null;
  4736. } // function TRIMSPACES()
  4737. private static $_invalidChars = Null;
  4738. /**
  4739. * TRIMNONPRINTABLE
  4740. *
  4741. * @param mixed $value Value to check
  4742. * @return string
  4743. */
  4744. public static function TRIMNONPRINTABLE($stringValue = '') {
  4745. $stringValue = self::flattenSingleValue($stringValue);
  4746. if (is_bool($stringValue)) {
  4747. $stringValue = ($stringValue) ? 'TRUE' : 'FALSE';
  4748. }
  4749. if (self::$_invalidChars == Null) {
  4750. self::$_invalidChars = range(chr(0),chr(31));
  4751. }
  4752. if (is_string($stringValue) || is_numeric($stringValue)) {
  4753. return str_replace(self::$_invalidChars,'',trim($stringValue,"\x00..\x1F"));
  4754. }
  4755. return Null;
  4756. } // function TRIMNONPRINTABLE()
  4757. /**
  4758. * ERROR_TYPE
  4759. *
  4760. * @param mixed $value Value to check
  4761. * @return boolean
  4762. */
  4763. public static function ERROR_TYPE($value = '') {
  4764. $value = self::flattenSingleValue($value);
  4765. $i = 1;
  4766. foreach(self::$_errorCodes as $errorCode) {
  4767. if ($value == $errorCode) {
  4768. return $i;
  4769. }
  4770. ++$i;
  4771. }
  4772. return self::$_errorCodes['na'];
  4773. } // function ERROR_TYPE()
  4774. /**
  4775. * IS_BLANK
  4776. *
  4777. * @param mixed $value Value to check
  4778. * @return boolean
  4779. */
  4780. public static function IS_BLANK($value=null) {
  4781. if (!is_null($value)) {
  4782. $value = self::flattenSingleValue($value);
  4783. }
  4784. return is_null($value);
  4785. } // function IS_BLANK()
  4786. /**
  4787. * IS_ERR
  4788. *
  4789. * @param mixed $value Value to check
  4790. * @return boolean
  4791. */
  4792. public static function IS_ERR($value = '') {
  4793. $value = self::flattenSingleValue($value);
  4794. return self::IS_ERROR($value) && (!self::IS_NA($value));
  4795. } // function IS_ERR()
  4796. /**
  4797. * IS_ERROR
  4798. *
  4799. * @param mixed $value Value to check
  4800. * @return boolean
  4801. */
  4802. public static function IS_ERROR($value = '') {
  4803. $value = self::flattenSingleValue($value);
  4804. return in_array($value, array_values(self::$_errorCodes));
  4805. } // function IS_ERROR()
  4806. /**
  4807. * IS_NA
  4808. *
  4809. * @param mixed $value Value to check
  4810. * @return boolean
  4811. */
  4812. public static function IS_NA($value = '') {
  4813. $value = self::flattenSingleValue($value);
  4814. return ($value === self::$_errorCodes['na']);
  4815. } // function IS_NA()
  4816. /**
  4817. * IS_EVEN
  4818. *
  4819. * @param mixed $value Value to check
  4820. * @return boolean
  4821. */
  4822. public static function IS_EVEN($value = 0) {
  4823. $value = self::flattenSingleValue($value);
  4824. if ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) {
  4825. return self::$_errorCodes['value'];
  4826. }
  4827. return ($value % 2 == 0);
  4828. } // function IS_EVEN()
  4829. /**
  4830. * IS_ODD
  4831. *
  4832. * @param mixed $value Value to check
  4833. * @return boolean
  4834. */
  4835. public static function IS_ODD($value = null) {
  4836. $value = self::flattenSingleValue($value);
  4837. if ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) {
  4838. return self::$_errorCodes['value'];
  4839. }
  4840. return (abs($value) % 2 == 1);
  4841. } // function IS_ODD()
  4842. /**
  4843. * IS_NUMBER
  4844. *
  4845. * @param mixed $value Value to check
  4846. * @return boolean
  4847. */
  4848. public static function IS_NUMBER($value = 0) {
  4849. $value = self::flattenSingleValue($value);
  4850. if (is_string($value)) {
  4851. return False;
  4852. }
  4853. return is_numeric($value);
  4854. } // function IS_NUMBER()
  4855. /**
  4856. * IS_LOGICAL
  4857. *
  4858. * @param mixed $value Value to check
  4859. * @return boolean
  4860. */
  4861. public static function IS_LOGICAL($value = true) {
  4862. $value = self::flattenSingleValue($value);
  4863. return is_bool($value);
  4864. } // function IS_LOGICAL()
  4865. /**
  4866. * IS_TEXT
  4867. *
  4868. * @param mixed $value Value to check
  4869. * @return boolean
  4870. */
  4871. public static function IS_TEXT($value = '') {
  4872. $value = self::flattenSingleValue($value);
  4873. return is_string($value);
  4874. } // function IS_TEXT()
  4875. /**
  4876. * IS_NONTEXT
  4877. *
  4878. * @param mixed $value Value to check
  4879. * @return boolean
  4880. */
  4881. public static function IS_NONTEXT($value = '') {
  4882. return !self::IS_TEXT($value);
  4883. } // function IS_NONTEXT()
  4884. /**
  4885. * VERSION
  4886. *
  4887. * @return string Version information
  4888. */
  4889. public static function VERSION() {
  4890. return 'PHPExcel ##VERSION##, ##DATE##';
  4891. } // function VERSION()
  4892. /**
  4893. * DATE
  4894. *
  4895. * @param long $year
  4896. * @param long $month
  4897. * @param long $day
  4898. * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
  4899. * depending on the value of the ReturnDateType flag
  4900. */
  4901. public static function DATE($year = 0, $month = 1, $day = 1) {
  4902. $year = (integer) self::flattenSingleValue($year);
  4903. $month = (integer) self::flattenSingleValue($month);
  4904. $day = (integer) self::flattenSingleValue($day);
  4905. $baseYear = PHPExcel_Shared_Date::getExcelCalendar();
  4906. // Validate parameters
  4907. if ($year < ($baseYear-1900)) {
  4908. return self::$_errorCodes['num'];
  4909. }
  4910. if ((($baseYear-1900) != 0) && ($year < $baseYear) && ($year >= 1900)) {
  4911. return self::$_errorCodes['num'];
  4912. }
  4913. if (($year < $baseYear) && ($year >= ($baseYear-1900))) {
  4914. $year += 1900;
  4915. }
  4916. if ($month < 1) {
  4917. // Handle year/month adjustment if month < 1
  4918. --$month;
  4919. $year += ceil($month / 12) - 1;
  4920. $month = 13 - abs($month % 12);
  4921. } elseif ($month > 12) {
  4922. // Handle year/month adjustment if month > 12
  4923. $year += floor($month / 12);
  4924. $month = ($month % 12);
  4925. }
  4926. // Re-validate the year parameter after adjustments
  4927. if (($year < $baseYear) || ($year >= 10000)) {
  4928. return self::$_errorCodes['num'];
  4929. }
  4930. // Execute function
  4931. $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel($year, $month, $day);
  4932. switch (self::getReturnDateType()) {
  4933. case self::RETURNDATE_EXCEL : return (float) $excelDateValue;
  4934. break;
  4935. case self::RETURNDATE_PHP_NUMERIC : return (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateValue);
  4936. break;
  4937. case self::RETURNDATE_PHP_OBJECT : return PHPExcel_Shared_Date::ExcelToPHPObject($excelDateValue);
  4938. break;
  4939. }
  4940. } // function DATE()
  4941. /**
  4942. * TIME
  4943. *
  4944. * @param long $hour
  4945. * @param long $minute
  4946. * @param long $second
  4947. * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
  4948. * depending on the value of the ReturnDateType flag
  4949. */
  4950. public static function TIME($hour = 0, $minute = 0, $second = 0) {
  4951. $hour = self::flattenSingleValue($hour);
  4952. $minute = self::flattenSingleValue($minute);
  4953. $second = self::flattenSingleValue($second);
  4954. if ($hour == '') { $hour = 0; }
  4955. if ($minute == '') { $minute = 0; }
  4956. if ($second == '') { $second = 0; }
  4957. if ((!is_numeric($hour)) || (!is_numeric($minute)) || (!is_numeric($second))) {
  4958. return self::$_errorCodes['value'];
  4959. }
  4960. $hour = (integer) $hour;
  4961. $minute = (integer) $minute;
  4962. $second = (integer) $second;
  4963. if ($second < 0) {
  4964. $minute += floor($second / 60);
  4965. $second = 60 - abs($second % 60);
  4966. if ($second == 60) { $second = 0; }
  4967. } elseif ($second >= 60) {
  4968. $minute += floor($second / 60);
  4969. $second = $second % 60;
  4970. }
  4971. if ($minute < 0) {
  4972. $hour += floor($minute / 60);
  4973. $minute = 60 - abs($minute % 60);
  4974. if ($minute == 60) { $minute = 0; }
  4975. } elseif ($minute >= 60) {
  4976. $hour += floor($minute / 60);
  4977. $minute = $minute % 60;
  4978. }
  4979. if ($hour > 23) {
  4980. $hour = $hour % 24;
  4981. } elseif ($hour < 0) {
  4982. return self::$_errorCodes['num'];
  4983. }
  4984. // Execute function
  4985. switch (self::getReturnDateType()) {
  4986. case self::RETURNDATE_EXCEL : $date = 0;
  4987. $calendar = PHPExcel_Shared_Date::getExcelCalendar();
  4988. if ($calendar != PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900) {
  4989. $date = 1;
  4990. }
  4991. return (float) PHPExcel_Shared_Date::FormattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second);
  4992. break;
  4993. case self::RETURNDATE_PHP_NUMERIC : return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::FormattedPHPToExcel(1970, 1, 1, $hour-1, $minute, $second)); // -2147468400; // -2147472000 + 3600
  4994. break;
  4995. case self::RETURNDATE_PHP_OBJECT : $dayAdjust = 0;
  4996. if ($hour < 0) {
  4997. $dayAdjust = floor($hour / 24);
  4998. $hour = 24 - abs($hour % 24);
  4999. if ($hour == 24) { $hour = 0; }
  5000. } elseif ($hour >= 24) {
  5001. $dayAdjust = floor($hour / 24);
  5002. $hour = $hour % 24;
  5003. }
  5004. $phpDateObject = new DateTime('1900-01-01 '.$hour.':'.$minute.':'.$second);
  5005. if ($dayAdjust != 0) {
  5006. $phpDateObject->modify($dayAdjust.' days');
  5007. }
  5008. return $phpDateObject;
  5009. break;
  5010. }
  5011. } // function TIME()
  5012. /**
  5013. * DATEVALUE
  5014. *
  5015. * @param string $dateValue
  5016. * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
  5017. * depending on the value of the ReturnDateType flag
  5018. */
  5019. public static function DATEVALUE($dateValue = 1) {
  5020. $dateValue = str_replace(array('/','.',' '),array('-','-','-'),trim(self::flattenSingleValue($dateValue),'"'));
  5021. $yearFound = false;
  5022. $t1 = explode('-',$dateValue);
  5023. foreach($t1 as &$t) {
  5024. if ((is_numeric($t)) && (($t > 31) && ($t < 100))) {
  5025. if ($yearFound) {
  5026. return self::$_errorCodes['value'];
  5027. } else {
  5028. $t += 1900;
  5029. $yearFound = true;
  5030. }
  5031. }
  5032. }
  5033. unset($t);
  5034. $dateValue = implode('-',$t1);
  5035. $PHPDateArray = date_parse($dateValue);
  5036. if (($PHPDateArray === False) || ($PHPDateArray['error_count'] > 0)) {
  5037. $testVal1 = strtok($dateValue,'- ');
  5038. if ($testVal1 !== False) {
  5039. $testVal2 = strtok('- ');
  5040. if ($testVal2 !== False) {
  5041. $testVal3 = strtok('- ');
  5042. if ($testVal3 === False) {
  5043. $testVal3 = strftime('%Y');
  5044. }
  5045. } else {
  5046. return self::$_errorCodes['value'];
  5047. }
  5048. } else {
  5049. return self::$_errorCodes['value'];
  5050. }
  5051. $PHPDateArray = date_parse($testVal1.'-'.$testVal2.'-'.$testVal3);
  5052. if (($PHPDateArray === False) || ($PHPDateArray['error_count'] > 0)) {
  5053. $PHPDateArray = date_parse($testVal2.'-'.$testVal1.'-'.$testVal3);
  5054. if (($PHPDateArray === False) || ($PHPDateArray['error_count'] > 0)) {
  5055. return self::$_errorCodes['value'];
  5056. }
  5057. }
  5058. }
  5059. if (($PHPDateArray !== False) && ($PHPDateArray['error_count'] == 0)) {
  5060. // Execute function
  5061. if ($PHPDateArray['year'] == '') { $PHPDateArray['year'] = strftime('%Y'); }
  5062. if ($PHPDateArray['month'] == '') { $PHPDateArray['month'] = strftime('%m'); }
  5063. if ($PHPDateArray['day'] == '') { $PHPDateArray['day'] = strftime('%d'); }
  5064. $excelDateValue = floor(PHPExcel_Shared_Date::FormattedPHPToExcel($PHPDateArray['year'],$PHPDateArray['month'],$PHPDateArray['day'],$PHPDateArray['hour'],$PHPDateArray['minute'],$PHPDateArray['second']));
  5065. switch (self::getReturnDateType()) {
  5066. case self::RETURNDATE_EXCEL : return (float) $excelDateValue;
  5067. break;
  5068. case self::RETURNDATE_PHP_NUMERIC : return (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateValue);
  5069. break;
  5070. case self::RETURNDATE_PHP_OBJECT : return new DateTime($PHPDateArray['year'].'-'.$PHPDateArray['month'].'-'.$PHPDateArray['day'].' 00:00:00');
  5071. break;
  5072. }
  5073. }
  5074. return self::$_errorCodes['value'];
  5075. } // function DATEVALUE()
  5076. /**
  5077. * _getDateValue
  5078. *
  5079. * @param string $dateValue
  5080. * @return mixed Excel date/time serial value, or string if error
  5081. */
  5082. private static function _getDateValue($dateValue) {
  5083. if (!is_numeric($dateValue)) {
  5084. if ((is_string($dateValue)) && (self::$compatibilityMode == self::COMPATIBILITY_GNUMERIC)) {
  5085. return self::$_errorCodes['value'];
  5086. }
  5087. if ((is_object($dateValue)) && ($dateValue instanceof PHPExcel_Shared_Date::$dateTimeObjectType)) {
  5088. $dateValue = PHPExcel_Shared_Date::PHPToExcel($dateValue);
  5089. } else {
  5090. $saveReturnDateType = self::getReturnDateType();
  5091. self::setReturnDateType(self::RETURNDATE_EXCEL);
  5092. $dateValue = self::DATEVALUE($dateValue);
  5093. self::setReturnDateType($saveReturnDateType);
  5094. }
  5095. }
  5096. return $dateValue;
  5097. } // function _getDateValue()
  5098. /**
  5099. * TIMEVALUE
  5100. *
  5101. * @param string $timeValue
  5102. * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
  5103. * depending on the value of the ReturnDateType flag
  5104. */
  5105. public static function TIMEVALUE($timeValue) {
  5106. $timeValue = self::flattenSingleValue($timeValue);
  5107. if ((($PHPDateArray = date_parse($timeValue)) !== False) && ($PHPDateArray['error_count'] == 0)) {
  5108. if (self::$compatibilityMode == self::COMPATIBILITY_OPENOFFICE) {
  5109. $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel($PHPDateArray['year'],$PHPDateArray['month'],$PHPDateArray['day'],$PHPDateArray['hour'],$PHPDateArray['minute'],$PHPDateArray['second']);
  5110. } else {
  5111. $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel(1900,1,1,$PHPDateArray['hour'],$PHPDateArray['minute'],$PHPDateArray['second']) - 1;
  5112. }
  5113. switch (self::getReturnDateType()) {
  5114. case self::RETURNDATE_EXCEL : return (float) $excelDateValue;
  5115. break;
  5116. case self::RETURNDATE_PHP_NUMERIC : return (integer) $phpDateValue = PHPExcel_Shared_Date::ExcelToPHP($excelDateValue+25569) - 3600;;
  5117. break;
  5118. case self::RETURNDATE_PHP_OBJECT : return new DateTime('1900-01-01 '.$PHPDateArray['hour'].':'.$PHPDateArray['minute'].':'.$PHPDateArray['second']);
  5119. break;
  5120. }
  5121. }
  5122. return self::$_errorCodes['value'];
  5123. } // function TIMEVALUE()
  5124. /**
  5125. * _getTimeValue
  5126. *
  5127. * @param string $timeValue
  5128. * @return mixed Excel date/time serial value, or string if error
  5129. */
  5130. private static function _getTimeValue($timeValue) {
  5131. $saveReturnDateType = self::getReturnDateType();
  5132. self::setReturnDateType(self::RETURNDATE_EXCEL);
  5133. $timeValue = self::TIMEVALUE($timeValue);
  5134. self::setReturnDateType($saveReturnDateType);
  5135. return $timeValue;
  5136. } // function _getTimeValue()
  5137. /**
  5138. * DATETIMENOW
  5139. *
  5140. * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
  5141. * depending on the value of the ReturnDateType flag
  5142. */
  5143. public static function DATETIMENOW() {
  5144. $saveTimeZone = date_default_timezone_get();
  5145. date_default_timezone_set('UTC');
  5146. $retValue = False;
  5147. switch (self::getReturnDateType()) {
  5148. case self::RETURNDATE_EXCEL : $retValue = (float) PHPExcel_Shared_Date::PHPToExcel(time());
  5149. break;
  5150. case self::RETURNDATE_PHP_NUMERIC : $retValue = (integer) time();
  5151. break;
  5152. case self::RETURNDATE_PHP_OBJECT : $retValue = new DateTime();
  5153. break;
  5154. }
  5155. date_default_timezone_set($saveTimeZone);
  5156. return $retValue;
  5157. } // function DATETIMENOW()
  5158. /**
  5159. * DATENOW
  5160. *
  5161. * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
  5162. * depending on the value of the ReturnDateType flag
  5163. */
  5164. public static function DATENOW() {
  5165. $saveTimeZone = date_default_timezone_get();
  5166. date_default_timezone_set('UTC');
  5167. $retValue = False;
  5168. $excelDateTime = floor(PHPExcel_Shared_Date::PHPToExcel(time()));
  5169. switch (self::getReturnDateType()) {
  5170. case self::RETURNDATE_EXCEL : $retValue = (float) $excelDateTime;
  5171. break;
  5172. case self::RETURNDATE_PHP_NUMERIC : $retValue = (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateTime) - 3600;
  5173. break;
  5174. case self::RETURNDATE_PHP_OBJECT : $retValue = PHPExcel_Shared_Date::ExcelToPHPObject($excelDateTime);
  5175. break;
  5176. }
  5177. date_default_timezone_set($saveTimeZone);
  5178. return $retValue;
  5179. } // function DATENOW()
  5180. private static function _isLeapYear($year) {
  5181. return ((($year % 4) == 0) && (($year % 100) != 0) || (($year % 400) == 0));
  5182. } // function _isLeapYear()
  5183. private static function _dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, $methodUS) {
  5184. if ($startDay == 31) {
  5185. --$startDay;
  5186. } elseif ($methodUS && ($startMonth == 2 && ($startDay == 29 || ($startDay == 28 && !self::_isLeapYear($startYear))))) {
  5187. $startDay = 30;
  5188. }
  5189. if ($endDay == 31) {
  5190. if ($methodUS && $startDay != 30) {
  5191. $endDay = 1;
  5192. if ($endMonth == 12) {
  5193. ++$endYear;
  5194. $endMonth = 1;
  5195. } else {
  5196. ++$endMonth;
  5197. }
  5198. } else {
  5199. $endDay = 30;
  5200. }
  5201. }
  5202. return $endDay + $endMonth * 30 + $endYear * 360 - $startDay - $startMonth * 30 - $startYear * 360;
  5203. } // function _dateDiff360()
  5204. /**
  5205. * DAYS360
  5206. *
  5207. * @param long $startDate Excel date serial value or a standard date string
  5208. * @param long $endDate Excel date serial value or a standard date string
  5209. * @param boolean $method US or European Method
  5210. * @return long PHP date/time serial
  5211. */
  5212. public static function DAYS360($startDate = 0, $endDate = 0, $method = false) {
  5213. $startDate = self::flattenSingleValue($startDate);
  5214. $endDate = self::flattenSingleValue($endDate);
  5215. if (is_string($startDate = self::_getDateValue($startDate))) {
  5216. return self::$_errorCodes['value'];
  5217. }
  5218. if (is_string($endDate = self::_getDateValue($endDate))) {
  5219. return self::$_errorCodes['value'];
  5220. }
  5221. // Execute function
  5222. $PHPStartDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($startDate);
  5223. $startDay = $PHPStartDateObject->format('j');
  5224. $startMonth = $PHPStartDateObject->format('n');
  5225. $startYear = $PHPStartDateObject->format('Y');
  5226. $PHPEndDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($endDate);
  5227. $endDay = $PHPEndDateObject->format('j');
  5228. $endMonth = $PHPEndDateObject->format('n');
  5229. $endYear = $PHPEndDateObject->format('Y');
  5230. return self::_dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, !$method);
  5231. } // function DAYS360()
  5232. /**
  5233. * DATEDIF
  5234. *
  5235. * @param long $startDate Excel date serial value or a standard date string
  5236. * @param long $endDate Excel date serial value or a standard date string
  5237. * @param string $unit
  5238. * @return long Interval between the dates
  5239. */
  5240. public static function DATEDIF($startDate = 0, $endDate = 0, $unit = 'D') {
  5241. $startDate = self::flattenSingleValue($startDate);
  5242. $endDate = self::flattenSingleValue($endDate);
  5243. $unit = strtoupper(self::flattenSingleValue($unit));
  5244. if (is_string($startDate = self::_getDateValue($startDate))) {
  5245. return self::$_errorCodes['value'];
  5246. }
  5247. if (is_string($endDate = self::_getDateValue($endDate))) {
  5248. return self::$_errorCodes['value'];
  5249. }
  5250. // Validate parameters
  5251. if ($startDate >= $endDate) {
  5252. return self::$_errorCodes['num'];
  5253. }
  5254. // Execute function
  5255. $difference = $endDate - $startDate;
  5256. $PHPStartDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($startDate);
  5257. $startDays = $PHPStartDateObject->format('j');
  5258. $startMonths = $PHPStartDateObject->format('n');
  5259. $startYears = $PHPStartDateObject->format('Y');
  5260. $PHPEndDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($endDate);
  5261. $endDays = $PHPEndDateObject->format('j');
  5262. $endMonths = $PHPEndDateObject->format('n');
  5263. $endYears = $PHPEndDateObject->format('Y');
  5264. $retVal = self::$_errorCodes['num'];
  5265. switch ($unit) {
  5266. case 'D':
  5267. $retVal = intval($difference);
  5268. break;
  5269. case 'M':
  5270. $retVal = intval($endMonths - $startMonths) + (intval($endYears - $startYears) * 12);
  5271. // We're only interested in full months
  5272. if ($endDays < $startDays) {
  5273. --$retVal;
  5274. }
  5275. break;
  5276. case 'Y':
  5277. $retVal = intval($endYears - $startYears);
  5278. // We're only interested in full months
  5279. if ($endMonths < $startMonths) {
  5280. --$retVal;
  5281. } elseif (($endMonths == $startMonths) && ($endDays < $startDays)) {
  5282. --$retVal;
  5283. }
  5284. break;
  5285. case 'MD':
  5286. if ($endDays < $startDays) {
  5287. $retVal = $endDays;
  5288. $PHPEndDateObject->modify('-'.$endDays.' days');
  5289. $adjustDays = $PHPEndDateObject->format('j');
  5290. if ($adjustDays > $startDays) {
  5291. $retVal += ($adjustDays - $startDays);
  5292. }
  5293. } else {
  5294. $retVal = $endDays - $startDays;
  5295. }
  5296. break;
  5297. case 'YM':
  5298. $retVal = intval($endMonths - $startMonths);
  5299. if ($retVal < 0) $retVal = 12 + $retVal;
  5300. // We're only interested in full months
  5301. if ($endDays < $startDays) {
  5302. --$retVal;
  5303. }
  5304. break;
  5305. case 'YD':
  5306. $retVal = intval($difference);
  5307. if ($endYears > $startYears) {
  5308. while ($endYears > $startYears) {
  5309. $PHPEndDateObject->modify('-1 year');
  5310. $endYears = $PHPEndDateObject->format('Y');
  5311. }
  5312. $retVal = $PHPEndDateObject->format('z') - $PHPStartDateObject->format('z');
  5313. if ($retVal < 0) { $retVal += 365; }
  5314. }
  5315. break;
  5316. }
  5317. return $retVal;
  5318. } // function DATEDIF()
  5319. /**
  5320. * YEARFRAC
  5321. *
  5322. * Calculates the fraction of the year represented by the number of whole days between two dates (the start_date and the
  5323. * end_date). Use the YEARFRAC worksheet function to identify the proportion of a whole year's benefits or obligations
  5324. * to assign to a specific term.
  5325. *
  5326. * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer) or date object, or a standard date string
  5327. * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer) or date object, or a standard date string
  5328. * @param integer $method Method used for the calculation
  5329. * 0 or omitted US (NASD) 30/360
  5330. * 1 Actual/actual
  5331. * 2 Actual/360
  5332. * 3 Actual/365
  5333. * 4 European 30/360
  5334. * @return float fraction of the year
  5335. */
  5336. public static function YEARFRAC($startDate = 0, $endDate = 0, $method = 0) {
  5337. $startDate = self::flattenSingleValue($startDate);
  5338. $endDate = self::flattenSingleValue($endDate);
  5339. $method = self::flattenSingleValue($method);
  5340. if (is_string($startDate = self::_getDateValue($startDate))) {
  5341. return self::$_errorCodes['value'];
  5342. }
  5343. if (is_string($endDate = self::_getDateValue($endDate))) {
  5344. return self::$_errorCodes['value'];
  5345. }
  5346. if ((is_numeric($method)) && (!is_string($method))) {
  5347. switch($method) {
  5348. case 0 :
  5349. return self::DAYS360($startDate,$endDate) / 360;
  5350. break;
  5351. case 1 :
  5352. $startYear = self::YEAR($startDate);
  5353. $endYear = self::YEAR($endDate);
  5354. $leapDay = 0;
  5355. if (self::_isLeapYear($startYear) || self::_isLeapYear($endYear)) {
  5356. $leapDay = 1;
  5357. }
  5358. return self::DATEDIF($startDate,$endDate) / (365 + $leapDay);
  5359. break;
  5360. case 2 :
  5361. return self::DATEDIF($startDate,$endDate) / 360;
  5362. break;
  5363. case 3 :
  5364. return self::DATEDIF($startDate,$endDate) / 365;
  5365. break;
  5366. case 4 :
  5367. return self::DAYS360($startDate,$endDate,True) / 360;
  5368. break;
  5369. }
  5370. }
  5371. return self::$_errorCodes['value'];
  5372. } // function YEARFRAC()
  5373. /**
  5374. * NETWORKDAYS
  5375. *
  5376. * @param mixed Start date
  5377. * @param mixed End date
  5378. * @param array of mixed Optional Date Series
  5379. * @return long Interval between the dates
  5380. */
  5381. public static function NETWORKDAYS($startDate,$endDate) {
  5382. // Flush the mandatory start and end date that are referenced in the function definition
  5383. $dateArgs = self::flattenArray(func_get_args());
  5384. array_shift($dateArgs);
  5385. array_shift($dateArgs);
  5386. // Validate the start and end dates
  5387. if (is_string($startDate = $sDate = self::_getDateValue($startDate))) {
  5388. return self::$_errorCodes['value'];
  5389. }
  5390. if (is_string($endDate = $eDate = self::_getDateValue($endDate))) {
  5391. return self::$_errorCodes['value'];
  5392. }
  5393. if ($sDate > $eDate) {
  5394. $startDate = $eDate;
  5395. $endDate = $sDate;
  5396. }
  5397. // Execute function
  5398. $startDoW = 6 - self::DAYOFWEEK($startDate,2);
  5399. if ($startDoW < 0) { $startDoW = 0; }
  5400. $endDoW = self::DAYOFWEEK($endDate,2);
  5401. if ($endDoW >= 6) { $endDoW = 0; }
  5402. $wholeWeekDays = floor(($endDate - $startDate) / 7) * 5;
  5403. $partWeekDays = $endDoW + $startDoW;
  5404. if ($partWeekDays > 5) {
  5405. $partWeekDays -= 5;
  5406. }
  5407. // Test any extra holiday parameters
  5408. $holidayCountedArray = array();
  5409. foreach ($dateArgs as $holidayDate) {
  5410. if (is_string($holidayDate = self::_getDateValue($holidayDate))) {
  5411. return self::$_errorCodes['value'];
  5412. }
  5413. if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) {
  5414. if ((self::DAYOFWEEK($holidayDate,2) < 6) && (!in_array($holidayDate,$holidayCountedArray))) {
  5415. --$partWeekDays;
  5416. $holidayCountedArray[] = $holidayDate;
  5417. }
  5418. }
  5419. }
  5420. if ($sDate > $eDate) {
  5421. return 0 - ($wholeWeekDays + $partWeekDays);
  5422. }
  5423. return $wholeWeekDays + $partWeekDays;
  5424. } // function NETWORKDAYS()
  5425. /**
  5426. * WORKDAY
  5427. *
  5428. * @param mixed Start date
  5429. * @param mixed number of days for adjustment
  5430. * @param array of mixed Optional Date Series
  5431. * @return long Interval between the dates
  5432. */
  5433. public static function WORKDAY($startDate,$endDays) {
  5434. $dateArgs = self::flattenArray(func_get_args());
  5435. array_shift($dateArgs);
  5436. array_shift($dateArgs);
  5437. if (is_string($startDate = self::_getDateValue($startDate))) {
  5438. return self::$_errorCodes['value'];
  5439. }
  5440. if (!is_numeric($endDays)) {
  5441. return self::$_errorCodes['value'];
  5442. }
  5443. $endDate = (float) $startDate + (floor($endDays / 5) * 7) + ($endDays % 5);
  5444. if ($endDays < 0) {
  5445. $endDate += 7;
  5446. }
  5447. $endDoW = self::DAYOFWEEK($endDate,3);
  5448. if ($endDoW >= 5) {
  5449. if ($endDays >= 0) {
  5450. $endDate += (7 - $endDoW);
  5451. } else {
  5452. $endDate -= ($endDoW - 5);
  5453. }
  5454. }
  5455. // Test any extra holiday parameters
  5456. if (count($dateArgs) > 0) {
  5457. $holidayCountedArray = $holidayDates = array();
  5458. foreach ($dateArgs as $holidayDate) {
  5459. if (is_string($holidayDate = self::_getDateValue($holidayDate))) {
  5460. return self::$_errorCodes['value'];
  5461. }
  5462. $holidayDates[] = $holidayDate;
  5463. }
  5464. if ($endDays >= 0) {
  5465. sort($holidayDates, SORT_NUMERIC);
  5466. } else {
  5467. rsort($holidayDates, SORT_NUMERIC);
  5468. }
  5469. foreach ($holidayDates as $holidayDate) {
  5470. if ($endDays >= 0) {
  5471. if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) {
  5472. if ((self::DAYOFWEEK($holidayDate,2) < 6) && (!in_array($holidayDate,$holidayCountedArray))) {
  5473. ++$endDate;
  5474. $holidayCountedArray[] = $holidayDate;
  5475. }
  5476. }
  5477. } else {
  5478. if (($holidayDate <= $startDate) && ($holidayDate >= $endDate)) {
  5479. if ((self::DAYOFWEEK($holidayDate,2) < 6) && (!in_array($holidayDate,$holidayCountedArray))) {
  5480. --$endDate;
  5481. $holidayCountedArray[] = $holidayDate;
  5482. }
  5483. }
  5484. }
  5485. $endDoW = self::DAYOFWEEK($endDate,3);
  5486. if ($endDoW >= 5) {
  5487. if ($endDays >= 0) {
  5488. $endDate += (7 - $endDoW);
  5489. } else {
  5490. $endDate -= ($endDoW - 5);
  5491. }
  5492. }
  5493. }
  5494. }
  5495. switch (self::getReturnDateType()) {
  5496. case self::RETURNDATE_EXCEL : return (float) $endDate;
  5497. break;
  5498. case self::RETURNDATE_PHP_NUMERIC : return (integer) PHPExcel_Shared_Date::ExcelToPHP($endDate);
  5499. break;
  5500. case self::RETURNDATE_PHP_OBJECT : return PHPExcel_Shared_Date::ExcelToPHPObject($endDate);
  5501. break;
  5502. }
  5503. } // function WORKDAY()
  5504. /**
  5505. * DAYOFMONTH
  5506. *
  5507. * @param long $dateValue Excel date serial value or a standard date string
  5508. * @return int Day
  5509. */
  5510. public static function DAYOFMONTH($dateValue = 1) {
  5511. $dateValue = self::flattenSingleValue($dateValue);
  5512. if (is_string($dateValue = self::_getDateValue($dateValue))) {
  5513. return self::$_errorCodes['value'];
  5514. } elseif ($dateValue == 0.0) {
  5515. return 0;
  5516. } elseif ($dateValue < 0.0) {
  5517. return self::$_errorCodes['num'];
  5518. }
  5519. // Execute function
  5520. $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
  5521. return (int) $PHPDateObject->format('j');
  5522. } // function DAYOFMONTH()
  5523. /**
  5524. * DAYOFWEEK
  5525. *
  5526. * @param long $dateValue Excel date serial value or a standard date string
  5527. * @return int Day
  5528. */
  5529. public static function DAYOFWEEK($dateValue = 1, $style = 1) {
  5530. $dateValue = self::flattenSingleValue($dateValue);
  5531. $style = floor(self::flattenSingleValue($style));
  5532. if (is_string($dateValue = self::_getDateValue($dateValue))) {
  5533. return self::$_errorCodes['value'];
  5534. } elseif ($dateValue < 0.0) {
  5535. return self::$_errorCodes['num'];
  5536. }
  5537. // Execute function
  5538. $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
  5539. $DoW = $PHPDateObject->format('w');
  5540. $firstDay = 1;
  5541. switch ($style) {
  5542. case 1: ++$DoW;
  5543. break;
  5544. case 2: if ($DoW == 0) { $DoW = 7; }
  5545. break;
  5546. case 3: if ($DoW == 0) { $DoW = 7; }
  5547. $firstDay = 0;
  5548. --$DoW;
  5549. break;
  5550. default:
  5551. }
  5552. if (self::$compatibilityMode == self::COMPATIBILITY_EXCEL) {
  5553. // Test for Excel's 1900 leap year, and introduce the error as required
  5554. if (($PHPDateObject->format('Y') == 1900) && ($PHPDateObject->format('n') <= 2)) {
  5555. --$DoW;
  5556. if ($DoW < $firstDay) {
  5557. $DoW += 7;
  5558. }
  5559. }
  5560. }
  5561. return (int) $DoW;
  5562. } // function DAYOFWEEK()
  5563. /**
  5564. * WEEKOFYEAR
  5565. *
  5566. * @param long $dateValue Excel date serial value or a standard date string
  5567. * @param boolean $method Week begins on Sunday or Monday
  5568. * @return int Week Number
  5569. */
  5570. public static function WEEKOFYEAR($dateValue = 1, $method = 1) {
  5571. $dateValue = self::flattenSingleValue($dateValue);
  5572. $method = floor(self::flattenSingleValue($method));
  5573. if (!is_numeric($method)) {
  5574. return self::$_errorCodes['value'];
  5575. } elseif (($method < 1) || ($method > 2)) {
  5576. return self::$_errorCodes['num'];
  5577. }
  5578. if (is_string($dateValue = self::_getDateValue($dateValue))) {
  5579. return self::$_errorCodes['value'];
  5580. } elseif ($dateValue < 0.0) {
  5581. return self::$_errorCodes['num'];
  5582. }
  5583. // Execute function
  5584. $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
  5585. $dayOfYear = $PHPDateObject->format('z');
  5586. $dow = $PHPDateObject->format('w');
  5587. $PHPDateObject->modify('-'.$dayOfYear.' days');
  5588. $dow = $PHPDateObject->format('w');
  5589. $daysInFirstWeek = 7 - (($dow + (2 - $method)) % 7);
  5590. $dayOfYear -= $daysInFirstWeek;
  5591. $weekOfYear = ceil($dayOfYear / 7) + 1;
  5592. return (int) $weekOfYear;
  5593. } // function WEEKOFYEAR()
  5594. /**
  5595. * MONTHOFYEAR
  5596. *
  5597. * @param long $dateValue Excel date serial value or a standard date string
  5598. * @return int Month
  5599. */
  5600. public static function MONTHOFYEAR($dateValue = 1) {
  5601. $dateValue = self::flattenSingleValue($dateValue);
  5602. if (is_string($dateValue = self::_getDateValue($dateValue))) {
  5603. return self::$_errorCodes['value'];
  5604. } elseif ($dateValue < 0.0) {
  5605. return self::$_errorCodes['num'];
  5606. }
  5607. // Execute function
  5608. $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
  5609. return (int) $PHPDateObject->format('n');
  5610. } // function MONTHOFYEAR()
  5611. /**
  5612. * YEAR
  5613. *
  5614. * @param long $dateValue Excel date serial value or a standard date string
  5615. * @return int Year
  5616. */
  5617. public static function YEAR($dateValue = 1) {
  5618. $dateValue = self::flattenSingleValue($dateValue);
  5619. if (is_string($dateValue = self::_getDateValue($dateValue))) {
  5620. return self::$_errorCodes['value'];
  5621. } elseif ($dateValue < 0.0) {
  5622. return self::$_errorCodes['num'];
  5623. }
  5624. // Execute function
  5625. $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
  5626. return (int) $PHPDateObject->format('Y');
  5627. } // function YEAR()
  5628. /**
  5629. * HOUROFDAY
  5630. *
  5631. * @param mixed $timeValue Excel time serial value or a standard time string
  5632. * @return int Hour
  5633. */
  5634. public static function HOUROFDAY($timeValue = 0) {
  5635. $timeValue = self::flattenSingleValue($timeValue);
  5636. if (!is_numeric($timeValue)) {
  5637. if (self::$compatibilityMode == self::COMPATIBILITY_GNUMERIC) {
  5638. $testVal = strtok($timeValue,'/-: ');
  5639. if (strlen($testVal) < strlen($timeValue)) {
  5640. return self::$_errorCodes['value'];
  5641. }
  5642. }
  5643. $timeValue = self::_getTimeValue($timeValue);
  5644. if (is_string($timeValue)) {
  5645. return self::$_errorCodes['value'];
  5646. }
  5647. }
  5648. // Execute function
  5649. if ($timeValue >= 1) {
  5650. $timeValue = fmod($timeValue,1);
  5651. } elseif ($timeValue < 0.0) {
  5652. return self::$_errorCodes['num'];
  5653. }
  5654. $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue);
  5655. return (int) gmdate('G',$timeValue);
  5656. } // function HOUROFDAY()
  5657. /**
  5658. * MINUTEOFHOUR
  5659. *
  5660. * @param long $timeValue Excel time serial value or a standard time string
  5661. * @return int Minute
  5662. */
  5663. public static function MINUTEOFHOUR($timeValue = 0) {
  5664. $timeValue = $timeTester = self::flattenSingleValue($timeValue);
  5665. if (!is_numeric($timeValue)) {
  5666. if (self::$compatibilityMode == self::COMPATIBILITY_GNUMERIC) {
  5667. $testVal = strtok($timeValue,'/-: ');
  5668. if (strlen($testVal) < strlen($timeValue)) {
  5669. return self::$_errorCodes['value'];
  5670. }
  5671. }
  5672. $timeValue = self::_getTimeValue($timeValue);
  5673. if (is_string($timeValue)) {
  5674. return self::$_errorCodes['value'];
  5675. }
  5676. }
  5677. // Execute function
  5678. if ($timeValue >= 1) {
  5679. $timeValue = fmod($timeValue,1);
  5680. } elseif ($timeValue < 0.0) {
  5681. return self::$_errorCodes['num'];
  5682. }
  5683. $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue);
  5684. return (int) gmdate('i',$timeValue);
  5685. } // function MINUTEOFHOUR()
  5686. /**
  5687. * SECONDOFMINUTE
  5688. *
  5689. * @param long $timeValue Excel time serial value or a standard time string
  5690. * @return int Second
  5691. */
  5692. public static function SECONDOFMINUTE($timeValue = 0) {
  5693. $timeValue = self::flattenSingleValue($timeValue);
  5694. if (!is_numeric($timeValue)) {
  5695. if (self::$compatibilityMode == self::COMPATIBILITY_GNUMERIC) {
  5696. $testVal = strtok($timeValue,'/-: ');
  5697. if (strlen($testVal) < strlen($timeValue)) {
  5698. return self::$_errorCodes['value'];
  5699. }
  5700. }
  5701. $timeValue = self::_getTimeValue($timeValue);
  5702. if (is_string($timeValue)) {
  5703. return self::$_errorCodes['value'];
  5704. }
  5705. }
  5706. // Execute function
  5707. if ($timeValue >= 1) {
  5708. $timeValue = fmod($timeValue,1);
  5709. } elseif ($timeValue < 0.0) {
  5710. return self::$_errorCodes['num'];
  5711. }
  5712. $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue);
  5713. return (int) gmdate('s',$timeValue);
  5714. } // function SECONDOFMINUTE()
  5715. private static function _adjustDateByMonths($dateValue = 0, $adjustmentMonths = 0) {
  5716. // Execute function
  5717. $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
  5718. $oMonth = (int) $PHPDateObject->format('m');
  5719. $oYear = (int) $PHPDateObject->format('Y');
  5720. $adjustmentMonthsString = (string) $adjustmentMonths;
  5721. if ($adjustmentMonths > 0) {
  5722. $adjustmentMonthsString = '+'.$adjustmentMonths;
  5723. }
  5724. if ($adjustmentMonths != 0) {
  5725. $PHPDateObject->modify($adjustmentMonthsString.' months');
  5726. }
  5727. $nMonth = (int) $PHPDateObject->format('m');
  5728. $nYear = (int) $PHPDateObject->format('Y');
  5729. $monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12);
  5730. if ($monthDiff != $adjustmentMonths) {
  5731. $adjustDays = (int) $PHPDateObject->format('d');
  5732. $adjustDaysString = '-'.$adjustDays.' days';
  5733. $PHPDateObject->modify($adjustDaysString);
  5734. }
  5735. return $PHPDateObject;
  5736. } // function _adjustDateByMonths()
  5737. /**
  5738. * EDATE
  5739. *
  5740. * Returns the serial number that represents the date that is the indicated number of months before or after a specified date
  5741. * (the start_date). Use EDATE to calculate maturity dates or due dates that fall on the same day of the month as the date of issue.
  5742. *
  5743. * @param long $dateValue Excel date serial value or a standard date string
  5744. * @param int $adjustmentMonths Number of months to adjust by
  5745. * @return long Excel date serial value
  5746. */
  5747. public static function EDATE($dateValue = 1, $adjustmentMonths = 0) {
  5748. $dateValue = self::flattenSingleValue($dateValue);
  5749. $adjustmentMonths = floor(self::flattenSingleValue($adjustmentMonths));
  5750. if (!is_numeric($adjustmentMonths)) {
  5751. return self::$_errorCodes['value'];
  5752. }
  5753. if (is_string($dateValue = self::_getDateValue($dateValue))) {
  5754. return self::$_errorCodes['value'];
  5755. }
  5756. // Execute function
  5757. $PHPDateObject = self::_adjustDateByMonths($dateValue,$adjustmentMonths);
  5758. switch (self::getReturnDateType()) {
  5759. case self::RETURNDATE_EXCEL : return (float) PHPExcel_Shared_Date::PHPToExcel($PHPDateObject);
  5760. break;
  5761. case self::RETURNDATE_PHP_NUMERIC : return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::PHPToExcel($PHPDateObject));
  5762. break;
  5763. case self::RETURNDATE_PHP_OBJECT : return $PHPDateObject;
  5764. break;
  5765. }
  5766. } // function EDATE()
  5767. /**
  5768. * EOMONTH
  5769. *
  5770. * Returns the serial number for the last day of the month that is the indicated number of months before or after start_date.
  5771. * Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month.
  5772. *
  5773. * @param long $dateValue Excel date serial value or a standard date string
  5774. * @param int $adjustmentMonths Number of months to adjust by
  5775. * @return long Excel date serial value
  5776. */
  5777. public static function EOMONTH($dateValue = 1, $adjustmentMonths = 0) {
  5778. $dateValue = self::flattenSingleValue($dateValue);
  5779. $adjustmentMonths = floor(self::flattenSingleValue($adjustmentMonths));
  5780. if (!is_numeric($adjustmentMonths)) {
  5781. return self::$_errorCodes['value'];
  5782. }
  5783. if (is_string($dateValue = self::_getDateValue($dateValue))) {
  5784. return self::$_errorCodes['value'];
  5785. }
  5786. // Execute function
  5787. $PHPDateObject = self::_adjustDateByMonths($dateValue,$adjustmentMonths+1);
  5788. $adjustDays = (int) $PHPDateObject->format('d');
  5789. $adjustDaysString = '-'.$adjustDays.' days';
  5790. $PHPDateObject->modify($adjustDaysString);
  5791. switch (self::getReturnDateType()) {
  5792. case self::RETURNDATE_EXCEL : return (float) PHPExcel_Shared_Date::PHPToExcel($PHPDateObject);
  5793. break;
  5794. case self::RETURNDATE_PHP_NUMERIC : return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::PHPToExcel($PHPDateObject));
  5795. break;
  5796. case self::RETURNDATE_PHP_OBJECT : return $PHPDateObject;
  5797. break;
  5798. }
  5799. } // function EOMONTH()
  5800. /**
  5801. * TRUNC
  5802. *
  5803. * Truncates value to the number of fractional digits by number_digits.
  5804. *
  5805. * @param float $value
  5806. * @param int $number_digits
  5807. * @return float Truncated value
  5808. */
  5809. public static function TRUNC($value = 0, $number_digits = 0) {
  5810. $value = self::flattenSingleValue($value);
  5811. $number_digits = self::flattenSingleValue($number_digits);
  5812. // Validate parameters
  5813. if ($number_digits < 0) {
  5814. return self::$_errorCodes['value'];
  5815. }
  5816. // Truncate
  5817. if ($number_digits > 0) {
  5818. $value = $value * pow(10, $number_digits);
  5819. }
  5820. $value = intval($value);
  5821. if ($number_digits > 0) {
  5822. $value = $value / pow(10, $number_digits);
  5823. }
  5824. // Return
  5825. return $value;
  5826. } // function TRUNC()
  5827. /**
  5828. * POWER
  5829. *
  5830. * Computes x raised to the power y.
  5831. *
  5832. * @param float $x
  5833. * @param float $y
  5834. * @return float
  5835. */
  5836. public static function POWER($x = 0, $y = 2) {
  5837. $x = self::flattenSingleValue($x);
  5838. $y = self::flattenSingleValue($y);
  5839. // Validate parameters
  5840. if ($x == 0 && $y <= 0) {
  5841. return self::$_errorCodes['divisionbyzero'];
  5842. }
  5843. // Return
  5844. return pow($x, $y);
  5845. } // function POWER()
  5846. private static function _nbrConversionFormat($xVal,$places) {
  5847. if (!is_null($places)) {
  5848. if (strlen($xVal) <= $places) {
  5849. return substr(str_pad($xVal,$places,'0',STR_PAD_LEFT),-10);
  5850. } else {
  5851. return self::$_errorCodes['num'];
  5852. }
  5853. }
  5854. return substr($xVal,-10);
  5855. } // function _nbrConversionFormat()
  5856. /**
  5857. * BINTODEC
  5858. *
  5859. * Return a binary value as Decimal.
  5860. *
  5861. * @param string $x
  5862. * @return string
  5863. */
  5864. public static function BINTODEC($x) {
  5865. $x = self::flattenSingleValue($x);
  5866. if (is_bool($x)) {
  5867. if (self::$compatibilityMode == self::COMPATIBILITY_OPENOFFICE) {
  5868. $x = (int) $x;
  5869. } else {
  5870. return self::$_errorCodes['value'];
  5871. }
  5872. }
  5873. if (self::$compatibilityMode == self::COMPATIBILITY_GNUMERIC) {
  5874. $x = floor($x);
  5875. }
  5876. $x = (string) $x;
  5877. if (strlen($x) > preg_match_all('/[01]/',$x,$out)) {
  5878. return self::$_errorCodes['num'];
  5879. }
  5880. if (strlen($x) > 10) {
  5881. return self::$_errorCodes['num'];
  5882. } elseif (strlen($x) == 10) {
  5883. // Two's Complement
  5884. $x = substr($x,-9);
  5885. return '-'.(512-bindec($x));
  5886. }
  5887. return bindec($x);
  5888. } // function BINTODEC()
  5889. /**
  5890. * BINTOHEX
  5891. *
  5892. * Return a binary value as Hex.
  5893. *
  5894. * @param string $x
  5895. * @return string
  5896. */
  5897. public static function BINTOHEX($x, $places=null) {
  5898. $x = floor(self::flattenSingleValue($x));
  5899. $places = self::flattenSingleValue($places);
  5900. if (is_bool($x)) {
  5901. if (self::$compatibilityMode == self::COMPATIBILITY_OPENOFFICE) {
  5902. $x = (int) $x;
  5903. } else {
  5904. return self::$_errorCodes['value'];
  5905. }
  5906. }
  5907. if (self::$compatibilityMode == self::COMPATIBILITY_GNUMERIC) {
  5908. $x = floor($x);
  5909. }
  5910. $x = (string) $x;
  5911. if (strlen($x) > preg_match_all('/[01]/',$x,$out)) {
  5912. return self::$_errorCodes['num'];
  5913. }
  5914. if (strlen($x) > 10) {
  5915. return self::$_errorCodes['num'];
  5916. } elseif (strlen($x) == 10) {
  5917. // Two's Complement
  5918. return str_repeat('F',8).substr(strtoupper(dechex(bindec(substr($x,-9)))),-2);
  5919. }
  5920. $hexVal = (string) strtoupper(dechex(bindec($x)));
  5921. return self::_nbrConversionFormat($hexVal,$places);
  5922. } // function BINTOHEX()
  5923. /**
  5924. * BINTOOCT
  5925. *
  5926. * Return a binary value as Octal.
  5927. *
  5928. * @param string $x
  5929. * @return string
  5930. */
  5931. public static function BINTOOCT($x, $places=null) {
  5932. $x = floor(self::flattenSingleValue($x));
  5933. $places = self::flattenSingleValue($places);
  5934. if (is_bool($x)) {
  5935. if (self::$compatibilityMode == self::COMPATIBILITY_OPENOFFICE) {
  5936. $x = (int) $x;
  5937. } else {
  5938. return self::$_errorCodes['value'];
  5939. }
  5940. }
  5941. if (self::$compatibilityMode == self::COMPATIBILITY_GNUMERIC) {
  5942. $x = floor($x);
  5943. }
  5944. $x = (string) $x;
  5945. if (strlen($x) > preg_match_all('/[01]/',$x,$out)) {
  5946. return self::$_errorCodes['num'];
  5947. }
  5948. if (strlen($x) > 10) {
  5949. return self::$_errorCodes['num'];
  5950. } elseif (strlen($x) == 10) {
  5951. // Two's Complement
  5952. return str_repeat('7',7).substr(strtoupper(decoct(bindec(substr($x,-9)))),-3);
  5953. }
  5954. $octVal = (string) decoct(bindec($x));
  5955. return self::_nbrConversionFormat($octVal,$places);
  5956. } // function BINTOOCT()
  5957. /**
  5958. * DECTOBIN
  5959. *
  5960. * Return an octal value as binary.
  5961. *
  5962. * @param string $x
  5963. * @return string
  5964. */
  5965. public static function DECTOBIN($x, $places=null) {
  5966. $x = self::flattenSingleValue($x);
  5967. $places = self::flattenSingleValue($places);
  5968. if (is_bool($x)) {
  5969. if (self::$compatibilityMode == self::COMPATIBILITY_OPENOFFICE) {
  5970. $x = (int) $x;
  5971. } else {
  5972. return self::$_errorCodes['value'];
  5973. }
  5974. }
  5975. $x = (string) $x;
  5976. if (strlen($x) > preg_match_all('/[-0123456789.]/',$x,$out)) {
  5977. return self::$_errorCodes['value'];
  5978. }
  5979. $x = (string) floor($x);
  5980. $r = decbin($x);
  5981. if (strlen($r) == 32) {
  5982. // Two's Complement
  5983. $r = substr($r,-10);
  5984. } elseif (strlen($r) > 11) {
  5985. return self::$_errorCodes['num'];
  5986. }
  5987. return self::_nbrConversionFormat($r,$places);
  5988. } // function DECTOBIN()
  5989. /**
  5990. * DECTOOCT
  5991. *
  5992. * Return an octal value as binary.
  5993. *
  5994. * @param string $x
  5995. * @return string
  5996. */
  5997. public static function DECTOOCT($x, $places=null) {
  5998. $x = self::flattenSingleValue($x);
  5999. $places = self::flattenSingleValue($places);
  6000. if (is_bool($x)) {
  6001. if (self::$compatibilityMode == self::COMPATIBILITY_OPENOFFICE) {
  6002. $x = (int) $x;
  6003. } else {
  6004. return self::$_errorCodes['value'];
  6005. }
  6006. }
  6007. $x = (string) $x;
  6008. if (strlen($x) > preg_match_all('/[-0123456789.]/',$x,$out)) {
  6009. return self::$_errorCodes['value'];
  6010. }
  6011. $x = (string) floor($x);
  6012. $r = decoct($x);
  6013. if (strlen($r) == 11) {
  6014. // Two's Complement
  6015. $r = substr($r,-10);
  6016. }
  6017. return self::_nbrConversionFormat($r,$places);
  6018. } // function DECTOOCT()
  6019. /**
  6020. * DECTOHEX
  6021. *
  6022. * Return an octal value as binary.
  6023. *
  6024. * @param string $x
  6025. * @return string
  6026. */
  6027. public static function DECTOHEX($x, $places=null) {
  6028. $x = self::flattenSingleValue($x);
  6029. $places = self::flattenSingleValue($places);
  6030. if (is_bool($x)) {
  6031. if (self::$compatibilityMode == self::COMPATIBILITY_OPENOFFICE) {
  6032. $x = (int) $x;
  6033. } else {
  6034. return self::$_errorCodes['value'];
  6035. }
  6036. }
  6037. $x = (string) $x;
  6038. if (strlen($x) > preg_match_all('/[-0123456789.]/',$x,$out)) {
  6039. return self::$_errorCodes['value'];
  6040. }
  6041. $x = (string) floor($x);
  6042. $r = strtoupper(dechex($x));
  6043. if (strlen($r) == 8) {
  6044. // Two's Complement
  6045. $r = 'FF'.$r;
  6046. }
  6047. return self::_nbrConversionFormat($r,$places);
  6048. } // function DECTOHEX()
  6049. /**
  6050. * HEXTOBIN
  6051. *
  6052. * Return a hex value as binary.
  6053. *
  6054. * @param string $x
  6055. * @return string
  6056. */
  6057. public static function HEXTOBIN($x, $places=null) {
  6058. $x = self::flattenSingleValue($x);
  6059. $places = self::flattenSingleValue($places);
  6060. if (is_bool($x)) {
  6061. return self::$_errorCodes['value'];
  6062. }
  6063. $x = (string) $x;
  6064. if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/',strtoupper($x),$out)) {
  6065. return self::$_errorCodes['num'];
  6066. }
  6067. $binVal = decbin(hexdec($x));
  6068. return substr(self::_nbrConversionFormat($binVal,$places),-10);
  6069. } // function HEXTOBIN()
  6070. /**
  6071. * HEXTOOCT
  6072. *
  6073. * Return a hex value as octal.
  6074. *
  6075. * @param string $x
  6076. * @return string
  6077. */
  6078. public static function HEXTOOCT($x, $places=null) {
  6079. $x = self::flattenSingleValue($x);
  6080. $places = self::flattenSingleValue($places);
  6081. if (is_bool($x)) {
  6082. return self::$_errorCodes['value'];
  6083. }
  6084. $x = (string) $x;
  6085. if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/',strtoupper($x),$out)) {
  6086. return self::$_errorCodes['num'];
  6087. }
  6088. $octVal = decoct(hexdec($x));
  6089. return self::_nbrConversionFormat($octVal,$places);
  6090. } // function HEXTOOCT()
  6091. /**
  6092. * HEXTODEC
  6093. *
  6094. * Return a hex value as octal.
  6095. *
  6096. * @param string $x
  6097. * @return string
  6098. */
  6099. public static function HEXTODEC($x) {
  6100. $x = self::flattenSingleValue($x);
  6101. if (is_bool($x)) {
  6102. return self::$_errorCodes['value'];
  6103. }
  6104. $x = (string) $x;
  6105. if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/',strtoupper($x),$out)) {
  6106. return self::$_errorCodes['num'];
  6107. }
  6108. return hexdec($x);
  6109. } // function HEXTODEC()
  6110. /**
  6111. * OCTTOBIN
  6112. *
  6113. * Return an octal value as binary.
  6114. *
  6115. * @param string $x
  6116. * @return string
  6117. */
  6118. public static function OCTTOBIN($x, $places=null) {
  6119. $x = self::flattenSingleValue($x);
  6120. $places = self::flattenSingleValue($places);
  6121. if (is_bool($x)) {
  6122. return self::$_errorCodes['value'];
  6123. }
  6124. $x = (string) $x;
  6125. if (preg_match_all('/[01234567]/',$x,$out) != strlen($x)) {
  6126. return self::$_errorCodes['num'];
  6127. }
  6128. $r = decbin(octdec($x));
  6129. return self::_nbrConversionFormat($r,$places);
  6130. } // function OCTTOBIN()
  6131. /**
  6132. * OCTTODEC
  6133. *
  6134. * Return an octal value as binary.
  6135. *
  6136. * @param string $x
  6137. * @return string
  6138. */
  6139. public static function OCTTODEC($x) {
  6140. $x = self::flattenSingleValue($x);
  6141. if (is_bool($x)) {
  6142. return self::$_errorCodes['value'];
  6143. }
  6144. $x = (string) $x;
  6145. if (preg_match_all('/[01234567]/',$x,$out) != strlen($x)) {
  6146. return self::$_errorCodes['num'];
  6147. }
  6148. return octdec($x);
  6149. } // function OCTTODEC()
  6150. /**
  6151. * OCTTOHEX
  6152. *
  6153. * Return an octal value as hex.
  6154. *
  6155. * @param string $x
  6156. * @return string
  6157. */
  6158. public static function OCTTOHEX($x, $places=null) {
  6159. $x = self::flattenSingleValue($x);
  6160. $places = self::flattenSingleValue($places);
  6161. if (is_bool($x)) {
  6162. return self::$_errorCodes['value'];
  6163. }
  6164. $x = (string) $x;
  6165. if (preg_match_all('/[01234567]/',$x,$out) != strlen($x)) {
  6166. return self::$_errorCodes['num'];
  6167. }
  6168. $hexVal = strtoupper(dechex(octdec($x)));
  6169. return self::_nbrConversionFormat($hexVal,$places);
  6170. } // function OCTTOHEX()
  6171. public static function _parseComplex($complexNumber) {
  6172. $workString = (string) $complexNumber;
  6173. $realNumber = $imaginary = 0;
  6174. // Extract the suffix, if there is one
  6175. $suffix = substr($workString,-1);
  6176. if (!is_numeric($suffix)) {
  6177. $workString = substr($workString,0,-1);
  6178. } else {
  6179. $suffix = '';
  6180. }
  6181. // Split the input into its Real and Imaginary components
  6182. $leadingSign = 0;
  6183. if (strlen($workString) > 0) {
  6184. $leadingSign = (($workString{0} == '+') || ($workString{0} == '-')) ? 1 : 0;
  6185. }
  6186. $power = '';
  6187. $realNumber = strtok($workString, '+-');
  6188. if (strtoupper(substr($realNumber,-1)) == 'E') {
  6189. $power = strtok('+-');
  6190. ++$leadingSign;
  6191. }
  6192. $realNumber = substr($workString,0,strlen($realNumber)+strlen($power)+$leadingSign);
  6193. if ($suffix != '') {
  6194. $imaginary = substr($workString,strlen($realNumber));
  6195. if (($imaginary == '') && (($realNumber == '') || ($realNumber == '+') || ($realNumber == '-'))) {
  6196. $imaginary = $realNumber.'1';
  6197. $realNumber = '0';
  6198. } else if ($imaginary == '') {
  6199. $imaginary = $realNumber;
  6200. $realNumber = '0';
  6201. } elseif (($imaginary == '+') || ($imaginary == '-')) {
  6202. $imaginary .= '1';
  6203. }
  6204. }
  6205. $complexArray = array( 'real' => $realNumber,
  6206. 'imaginary' => $imaginary,
  6207. 'suffix' => $suffix
  6208. );
  6209. return $complexArray;
  6210. } // function _parseComplex()
  6211. private static function _cleanComplex($complexNumber) {
  6212. if ($complexNumber{0} == '+') $complexNumber = substr($complexNumber,1);
  6213. if ($complexNumber{0} == '0') $complexNumber = substr($complexNumber,1);
  6214. if ($complexNumber{0} == '.') $complexNumber = '0'.$complexNumber;
  6215. if ($complexNumber{0} == '+') $complexNumber = substr($complexNumber,1);
  6216. return $complexNumber;
  6217. }
  6218. /**
  6219. * COMPLEX
  6220. *
  6221. * returns a complex number of the form x + yi or x + yj.
  6222. *
  6223. * @param float $realNumber
  6224. * @param float $imaginary
  6225. * @param string $suffix
  6226. * @return string
  6227. */
  6228. public static function COMPLEX($realNumber=0.0, $imaginary=0.0, $suffix='i') {
  6229. $realNumber = self::flattenSingleValue($realNumber);
  6230. $imaginary = self::flattenSingleValue($imaginary);
  6231. $suffix = self::flattenSingleValue($suffix);
  6232. if (((is_numeric($realNumber)) && (is_numeric($imaginary))) &&
  6233. (($suffix == 'i') || ($suffix == 'j') || ($suffix == ''))) {
  6234. if ($realNumber == 0.0) {
  6235. if ($imaginary == 0.0) {
  6236. return (string) '0';
  6237. } elseif ($imaginary == 1.0) {
  6238. return (string) $suffix;
  6239. } elseif ($imaginary == -1.0) {
  6240. return (string) '-'.$suffix;
  6241. }
  6242. return (string) $imaginary.$suffix;
  6243. } elseif ($imaginary == 0.0) {
  6244. return (string) $realNumber;
  6245. } elseif ($imaginary == 1.0) {
  6246. return (string) $realNumber.'+'.$suffix;
  6247. } elseif ($imaginary == -1.0) {
  6248. return (string) $realNumber.'-'.$suffix;
  6249. }
  6250. if ($imaginary > 0) { $imaginary = (string) '+'.$imaginary; }
  6251. return (string) $realNumber.$imaginary.$suffix;
  6252. }
  6253. return self::$_errorCodes['value'];
  6254. } // function COMPLEX()
  6255. /**
  6256. * IMAGINARY
  6257. *
  6258. * Returns the imaginary coefficient of a complex number in x + yi or x + yj text format.
  6259. *
  6260. * @param string $complexNumber
  6261. * @return real
  6262. */
  6263. public static function IMAGINARY($complexNumber) {
  6264. $complexNumber = self::flattenSingleValue($complexNumber);
  6265. $parsedComplex = self::_parseComplex($complexNumber);
  6266. if (!is_array($parsedComplex)) {
  6267. return $parsedComplex;
  6268. }
  6269. return $parsedComplex['imaginary'];
  6270. } // function IMAGINARY()
  6271. /**
  6272. * IMREAL
  6273. *
  6274. * Returns the real coefficient of a complex number in x + yi or x + yj text format.
  6275. *
  6276. * @param string $complexNumber
  6277. * @return real
  6278. */
  6279. public static function IMREAL($complexNumber) {
  6280. $complexNumber = self::flattenSingleValue($complexNumber);
  6281. $parsedComplex = self::_parseComplex($complexNumber);
  6282. if (!is_array($parsedComplex)) {
  6283. return $parsedComplex;
  6284. }
  6285. return $parsedComplex['real'];
  6286. } // function IMREAL()
  6287. /**
  6288. * IMABS
  6289. *
  6290. * Returns the absolute value (modulus) of a complex number in x + yi or x + yj text format.
  6291. *
  6292. * @param string $complexNumber
  6293. * @return real
  6294. */
  6295. public static function IMABS($complexNumber) {
  6296. $complexNumber = self::flattenSingleValue($complexNumber);
  6297. $parsedComplex = self::_parseComplex($complexNumber);
  6298. if (!is_array($parsedComplex)) {
  6299. return $parsedComplex;
  6300. }
  6301. return sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary']));
  6302. } // function IMABS()
  6303. /**
  6304. * IMARGUMENT
  6305. *
  6306. * Returns the argument theta of a complex number, i.e. the angle in radians from the real axis to the representation of the number in polar coordinates.
  6307. *
  6308. * @param string $complexNumber
  6309. * @return string
  6310. */
  6311. public static function IMARGUMENT($complexNumber) {
  6312. $complexNumber = self::flattenSingleValue($complexNumber);
  6313. $parsedComplex = self::_parseComplex($complexNumber);
  6314. if (!is_array($parsedComplex)) {
  6315. return $parsedComplex;
  6316. }
  6317. if ($parsedComplex['real'] == 0.0) {
  6318. if ($parsedComplex['imaginary'] == 0.0) {
  6319. return 0.0;
  6320. } elseif($parsedComplex['imaginary'] < 0.0) {
  6321. return M_PI / -2;
  6322. } else {
  6323. return M_PI / 2;
  6324. }
  6325. } elseif ($parsedComplex['real'] > 0.0) {
  6326. return atan($parsedComplex['imaginary'] / $parsedComplex['real']);
  6327. } elseif ($parsedComplex['imaginary'] < 0.0) {
  6328. return 0 - (M_PI - atan(abs($parsedComplex['imaginary']) / abs($parsedComplex['real'])));
  6329. } else {
  6330. return M_PI - atan($parsedComplex['imaginary'] / abs($parsedComplex['real']));
  6331. }
  6332. } // function IMARGUMENT()
  6333. /**
  6334. * IMCONJUGATE
  6335. *
  6336. * Returns the complex conjugate of a complex number in x + yi or x + yj text format.
  6337. *
  6338. * @param string $complexNumber
  6339. * @return string
  6340. */
  6341. public static function IMCONJUGATE($complexNumber) {
  6342. $complexNumber = self::flattenSingleValue($complexNumber);
  6343. $parsedComplex = self::_parseComplex($complexNumber);
  6344. if (!is_array($parsedComplex)) {
  6345. return $parsedComplex;
  6346. }
  6347. if ($parsedComplex['imaginary'] == 0.0) {
  6348. return $parsedComplex['real'];
  6349. } else {
  6350. return self::_cleanComplex(self::COMPLEX($parsedComplex['real'], 0 - $parsedComplex['imaginary'], $parsedComplex['suffix']));
  6351. }
  6352. } // function IMCONJUGATE()
  6353. /**
  6354. * IMCOS
  6355. *
  6356. * Returns the cosine of a complex number in x + yi or x + yj text format.
  6357. *
  6358. * @param string $complexNumber
  6359. * @return string
  6360. */
  6361. public static function IMCOS($complexNumber) {
  6362. $complexNumber = self::flattenSingleValue($complexNumber);
  6363. $parsedComplex = self::_parseComplex($complexNumber);
  6364. if (!is_array($parsedComplex)) {
  6365. return $parsedComplex;
  6366. }
  6367. if ($parsedComplex['imaginary'] == 0.0) {
  6368. return cos($parsedComplex['real']);
  6369. } else {
  6370. return self::IMCONJUGATE(self::COMPLEX(cos($parsedComplex['real']) * cosh($parsedComplex['imaginary']),sin($parsedComplex['real']) * sinh($parsedComplex['imaginary']),$parsedComplex['suffix']));
  6371. }
  6372. } // function IMCOS()
  6373. /**
  6374. * IMSIN
  6375. *
  6376. * Returns the sine of a complex number in x + yi or x + yj text format.
  6377. *
  6378. * @param string $complexNumber
  6379. * @return string
  6380. */
  6381. public static function IMSIN($complexNumber) {
  6382. $complexNumber = self::flattenSingleValue($complexNumber);
  6383. $parsedComplex = self::_parseComplex($complexNumber);
  6384. if (!is_array($parsedComplex)) {
  6385. return $parsedComplex;
  6386. }
  6387. if ($parsedComplex['imaginary'] == 0.0) {
  6388. return sin($parsedComplex['real']);
  6389. } else {
  6390. return self::COMPLEX(sin($parsedComplex['real']) * cosh($parsedComplex['imaginary']),cos($parsedComplex['real']) * sinh($parsedComplex['imaginary']),$parsedComplex['suffix']);
  6391. }
  6392. } // function IMSIN()
  6393. /**
  6394. * IMSQRT
  6395. *
  6396. * Returns the square root of a complex number in x + yi or x + yj text format.
  6397. *
  6398. * @param string $complexNumber
  6399. * @return string
  6400. */
  6401. public static function IMSQRT($complexNumber) {
  6402. $complexNumber = self::flattenSingleValue($complexNumber);
  6403. $parsedComplex = self::_parseComplex($complexNumber);
  6404. if (!is_array($parsedComplex)) {
  6405. return $parsedComplex;
  6406. }
  6407. $theta = self::IMARGUMENT($complexNumber);
  6408. $d1 = cos($theta / 2);
  6409. $d2 = sin($theta / 2);
  6410. $r = sqrt(sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary'])));
  6411. if ($parsedComplex['suffix'] == '') {
  6412. return self::COMPLEX($d1 * $r,$d2 * $r);
  6413. } else {
  6414. return self::COMPLEX($d1 * $r,$d2 * $r,$parsedComplex['suffix']);
  6415. }
  6416. } // function IMSQRT()
  6417. /**
  6418. * IMLN
  6419. *
  6420. * Returns the natural logarithm of a complex number in x + yi or x + yj text format.
  6421. *
  6422. * @param string $complexNumber
  6423. * @return string
  6424. */
  6425. public static function IMLN($complexNumber) {
  6426. $complexNumber = self::flattenSingleValue($complexNumber);
  6427. $parsedComplex = self::_parseComplex($complexNumber);
  6428. if (!is_array($parsedComplex)) {
  6429. return $parsedComplex;
  6430. }
  6431. if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
  6432. return self::$_errorCodes['num'];
  6433. }
  6434. $logR = log(sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary'])));
  6435. $t = self::IMARGUMENT($complexNumber);
  6436. if ($parsedComplex['suffix'] == '') {
  6437. return self::COMPLEX($logR,$t);
  6438. } else {
  6439. return self::COMPLEX($logR,$t,$parsedComplex['suffix']);
  6440. }
  6441. } // function IMLN()
  6442. /**
  6443. * IMLOG10
  6444. *
  6445. * Returns the common logarithm (base 10) of a complex number in x + yi or x + yj text format.
  6446. *
  6447. * @param string $complexNumber
  6448. * @return string
  6449. */
  6450. public static function IMLOG10($complexNumber) {
  6451. $complexNumber = self::flattenSingleValue($complexNumber);
  6452. $parsedComplex = self::_parseComplex($complexNumber);
  6453. if (!is_array($parsedComplex)) {
  6454. return $parsedComplex;
  6455. }
  6456. if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
  6457. return self::$_errorCodes['num'];
  6458. } elseif (($parsedComplex['real'] > 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
  6459. return log10($parsedComplex['real']);
  6460. }
  6461. return self::IMPRODUCT(log10(EULER),self::IMLN($complexNumber));
  6462. } // function IMLOG10()
  6463. /**
  6464. * IMLOG2
  6465. *
  6466. * Returns the common logarithm (base 10) of a complex number in x + yi or x + yj text format.
  6467. *
  6468. * @param string $complexNumber
  6469. * @return string
  6470. */
  6471. public static function IMLOG2($complexNumber) {
  6472. $complexNumber = self::flattenSingleValue($complexNumber);
  6473. $parsedComplex = self::_parseComplex($complexNumber);
  6474. if (!is_array($parsedComplex)) {
  6475. return $parsedComplex;
  6476. }
  6477. if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
  6478. return self::$_errorCodes['num'];
  6479. } elseif (($parsedComplex['real'] > 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
  6480. return log($parsedComplex['real'],2);
  6481. }
  6482. return self::IMPRODUCT(log(EULER,2),self::IMLN($complexNumber));
  6483. } // function IMLOG2()
  6484. /**
  6485. * IMEXP
  6486. *
  6487. * Returns the exponential of a complex number in x + yi or x + yj text format.
  6488. *
  6489. * @param string $complexNumber
  6490. * @return string
  6491. */
  6492. public static function IMEXP($complexNumber) {
  6493. $complexNumber = self::flattenSingleValue($complexNumber);
  6494. $parsedComplex = self::_parseComplex($complexNumber);
  6495. if (!is_array($parsedComplex)) {
  6496. return $parsedComplex;
  6497. }
  6498. if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
  6499. return '1';
  6500. }
  6501. $e = exp($parsedComplex['real']);
  6502. $eX = $e * cos($parsedComplex['imaginary']);
  6503. $eY = $e * sin($parsedComplex['imaginary']);
  6504. if ($parsedComplex['suffix'] == '') {
  6505. return self::COMPLEX($eX,$eY);
  6506. } else {
  6507. return self::COMPLEX($eX,$eY,$parsedComplex['suffix']);
  6508. }
  6509. } // function IMEXP()
  6510. /**
  6511. * IMPOWER
  6512. *
  6513. * Returns a complex number in x + yi or x + yj text format raised to a power.
  6514. *
  6515. * @param string $complexNumber
  6516. * @return string
  6517. */
  6518. public static function IMPOWER($complexNumber,$realNumber) {
  6519. $complexNumber = self::flattenSingleValue($complexNumber);
  6520. $realNumber = self::flattenSingleValue($realNumber);
  6521. if (!is_numeric($realNumber)) {
  6522. return self::$_errorCodes['value'];
  6523. }
  6524. $parsedComplex = self::_parseComplex($complexNumber);
  6525. if (!is_array($parsedComplex)) {
  6526. return $parsedComplex;
  6527. }
  6528. $r = sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary']));
  6529. $rPower = pow($r,$realNumber);
  6530. $theta = self::IMARGUMENT($complexNumber) * $realNumber;
  6531. if ($theta == 0) {
  6532. return 1;
  6533. } elseif ($parsedComplex['imaginary'] == 0.0) {
  6534. return self::COMPLEX($rPower * cos($theta),$rPower * sin($theta),$parsedComplex['suffix']);
  6535. } else {
  6536. return self::COMPLEX($rPower * cos($theta),$rPower * sin($theta),$parsedComplex['suffix']);
  6537. }
  6538. } // function IMPOWER()
  6539. /**
  6540. * IMDIV
  6541. *
  6542. * Returns the quotient of two complex numbers in x + yi or x + yj text format.
  6543. *
  6544. * @param string $complexDividend
  6545. * @param string $complexDivisor
  6546. * @return real
  6547. */
  6548. public static function IMDIV($complexDividend,$complexDivisor) {
  6549. $complexDividend = self::flattenSingleValue($complexDividend);
  6550. $complexDivisor = self::flattenSingleValue($complexDivisor);
  6551. $parsedComplexDividend = self::_parseComplex($complexDividend);
  6552. if (!is_array($parsedComplexDividend)) {
  6553. return $parsedComplexDividend;
  6554. }
  6555. $parsedComplexDivisor = self::_parseComplex($complexDivisor);
  6556. if (!is_array($parsedComplexDivisor)) {
  6557. return $parsedComplexDividend;
  6558. }
  6559. if (($parsedComplexDividend['suffix'] != '') && ($parsedComplexDivisor['suffix'] != '') &&
  6560. ($parsedComplexDividend['suffix'] != $parsedComplexDivisor['suffix'])) {
  6561. return self::$_errorCodes['num'];
  6562. }
  6563. if (($parsedComplexDividend['suffix'] != '') && ($parsedComplexDivisor['suffix'] == '')) {
  6564. $parsedComplexDivisor['suffix'] = $parsedComplexDividend['suffix'];
  6565. }
  6566. $d1 = ($parsedComplexDividend['real'] * $parsedComplexDivisor['real']) + ($parsedComplexDividend['imaginary'] * $parsedComplexDivisor['imaginary']);
  6567. $d2 = ($parsedComplexDividend['imaginary'] * $parsedComplexDivisor['real']) - ($parsedComplexDividend['real'] * $parsedComplexDivisor['imaginary']);
  6568. $d3 = ($parsedComplexDivisor['real'] * $parsedComplexDivisor['real']) + ($parsedComplexDivisor['imaginary'] * $parsedComplexDivisor['imaginary']);
  6569. $r = $d1/$d3;
  6570. $i = $d2/$d3;
  6571. if ($i > 0.0) {
  6572. return self::_cleanComplex($r.'+'.$i.$parsedComplexDivisor['suffix']);
  6573. } elseif ($i < 0.0) {
  6574. return self::_cleanComplex($r.$i.$parsedComplexDivisor['suffix']);
  6575. } else {
  6576. return $r;
  6577. }
  6578. } // function IMDIV()
  6579. /**
  6580. * IMSUB
  6581. *
  6582. * Returns the difference of two complex numbers in x + yi or x + yj text format.
  6583. *
  6584. * @param string $complexNumber1
  6585. * @param string $complexNumber2
  6586. * @return real
  6587. */
  6588. public static function IMSUB($complexNumber1,$complexNumber2) {
  6589. $complexNumber1 = self::flattenSingleValue($complexNumber1);
  6590. $complexNumber2 = self::flattenSingleValue($complexNumber2);
  6591. $parsedComplex1 = self::_parseComplex($complexNumber1);
  6592. if (!is_array($parsedComplex1)) {
  6593. return $parsedComplex1;
  6594. }
  6595. $parsedComplex2 = self::_parseComplex($complexNumber2);
  6596. if (!is_array($parsedComplex2)) {
  6597. return $parsedComplex2;
  6598. }
  6599. if ((($parsedComplex1['suffix'] != '') && ($parsedComplex2['suffix'] != '')) &&
  6600. ($parsedComplex1['suffix'] != $parsedComplex2['suffix'])) {
  6601. return self::$_errorCodes['num'];
  6602. } elseif (($parsedComplex1['suffix'] == '') && ($parsedComplex2['suffix'] != '')) {
  6603. $parsedComplex1['suffix'] = $parsedComplex2['suffix'];
  6604. }
  6605. $d1 = $parsedComplex1['real'] - $parsedComplex2['real'];
  6606. $d2 = $parsedComplex1['imaginary'] - $parsedComplex2['imaginary'];
  6607. return self::COMPLEX($d1,$d2,$parsedComplex1['suffix']);
  6608. } // function IMSUB()
  6609. /**
  6610. * IMSUM
  6611. *
  6612. * Returns the sum of two or more complex numbers in x + yi or x + yj text format.
  6613. *
  6614. * @param array of mixed Data Series
  6615. * @return real
  6616. */
  6617. public static function IMSUM() {
  6618. // Return value
  6619. $returnValue = self::_parseComplex('0');
  6620. $activeSuffix = '';
  6621. // Loop through the arguments
  6622. $aArgs = self::flattenArray(func_get_args());
  6623. foreach ($aArgs as $arg) {
  6624. $parsedComplex = self::_parseComplex($arg);
  6625. if (!is_array($parsedComplex)) {
  6626. return $parsedComplex;
  6627. }
  6628. if ($activeSuffix == '') {
  6629. $activeSuffix = $parsedComplex['suffix'];
  6630. } elseif (($parsedComplex['suffix'] != '') && ($activeSuffix != $parsedComplex['suffix'])) {
  6631. return self::$_errorCodes['value'];
  6632. }
  6633. $returnValue['real'] += $parsedComplex['real'];
  6634. $returnValue['imaginary'] += $parsedComplex['imaginary'];
  6635. }
  6636. if ($returnValue['imaginary'] == 0.0) { $activeSuffix = ''; }
  6637. return self::COMPLEX($returnValue['real'],$returnValue['imaginary'],$activeSuffix);
  6638. } // function IMSUM()
  6639. /**
  6640. * IMPRODUCT
  6641. *
  6642. * Returns the product of two or more complex numbers in x + yi or x + yj text format.
  6643. *
  6644. * @param array of mixed Data Series
  6645. * @return real
  6646. */
  6647. public static function IMPRODUCT() {
  6648. // Return value
  6649. $returnValue = self::_parseComplex('1');
  6650. $activeSuffix = '';
  6651. // Loop through the arguments
  6652. $aArgs = self::flattenArray(func_get_args());
  6653. foreach ($aArgs as $arg) {
  6654. $parsedComplex = self::_parseComplex($arg);
  6655. if (!is_array($parsedComplex)) {
  6656. return $parsedComplex;
  6657. }
  6658. $workValue = $returnValue;
  6659. if (($parsedComplex['suffix'] != '') && ($activeSuffix == '')) {
  6660. $activeSuffix = $parsedComplex['suffix'];
  6661. } elseif (($parsedComplex['suffix'] != '') && ($activeSuffix != $parsedComplex['suffix'])) {
  6662. return self::$_errorCodes['num'];
  6663. }
  6664. $returnValue['real'] = ($workValue['real'] * $parsedComplex['real']) - ($workValue['imaginary'] * $parsedComplex['imaginary']);
  6665. $returnValue['imaginary'] = ($workValue['real'] * $parsedComplex['imaginary']) + ($workValue['imaginary'] * $parsedComplex['real']);
  6666. }
  6667. if ($returnValue['imaginary'] == 0.0) { $activeSuffix = ''; }
  6668. return self::COMPLEX($returnValue['real'],$returnValue['imaginary'],$activeSuffix);
  6669. } // function IMPRODUCT()
  6670. private static $_conversionUnits = array( 'g' => array( 'Group' => 'Mass', 'Unit Name' => 'Gram', 'AllowPrefix' => True ),
  6671. 'sg' => array( 'Group' => 'Mass', 'Unit Name' => 'Slug', 'AllowPrefix' => False ),
  6672. 'lbm' => array( 'Group' => 'Mass', 'Unit Name' => 'Pound mass (avoirdupois)', 'AllowPrefix' => False ),
  6673. 'u' => array( 'Group' => 'Mass', 'Unit Name' => 'U (atomic mass unit)', 'AllowPrefix' => True ),
  6674. 'ozm' => array( 'Group' => 'Mass', 'Unit Name' => 'Ounce mass (avoirdupois)', 'AllowPrefix' => False ),
  6675. 'm' => array( 'Group' => 'Distance', 'Unit Name' => 'Meter', 'AllowPrefix' => True ),
  6676. 'mi' => array( 'Group' => 'Distance', 'Unit Name' => 'Statute mile', 'AllowPrefix' => False ),
  6677. 'Nmi' => array( 'Group' => 'Distance', 'Unit Name' => 'Nautical mile', 'AllowPrefix' => False ),
  6678. 'in' => array( 'Group' => 'Distance', 'Unit Name' => 'Inch', 'AllowPrefix' => False ),
  6679. 'ft' => array( 'Group' => 'Distance', 'Unit Name' => 'Foot', 'AllowPrefix' => False ),
  6680. 'yd' => array( 'Group' => 'Distance', 'Unit Name' => 'Yard', 'AllowPrefix' => False ),
  6681. 'ang' => array( 'Group' => 'Distance', 'Unit Name' => 'Angstrom', 'AllowPrefix' => True ),
  6682. 'Pica' => array( 'Group' => 'Distance', 'Unit Name' => 'Pica (1/72 in)', 'AllowPrefix' => False ),
  6683. 'yr' => array( 'Group' => 'Time', 'Unit Name' => 'Year', 'AllowPrefix' => False ),
  6684. 'day' => array( 'Group' => 'Time', 'Unit Name' => 'Day', 'AllowPrefix' => False ),
  6685. 'hr' => array( 'Group' => 'Time', 'Unit Name' => 'Hour', 'AllowPrefix' => False ),
  6686. 'mn' => array( 'Group' => 'Time', 'Unit Name' => 'Minute', 'AllowPrefix' => False ),
  6687. 'sec' => array( 'Group' => 'Time', 'Unit Name' => 'Second', 'AllowPrefix' => True ),
  6688. 'Pa' => array( 'Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => True ),
  6689. 'p' => array( 'Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => True ),
  6690. 'atm' => array( 'Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => True ),
  6691. 'at' => array( 'Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => True ),
  6692. 'mmHg' => array( 'Group' => 'Pressure', 'Unit Name' => 'mm of Mercury', 'AllowPrefix' => True ),
  6693. 'N' => array( 'Group' => 'Force', 'Unit Name' => 'Newton', 'AllowPrefix' => True ),
  6694. 'dyn' => array( 'Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => True ),
  6695. 'dy' => array( 'Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => True ),
  6696. 'lbf' => array( 'Group' => 'Force', 'Unit Name' => 'Pound force', 'AllowPrefix' => False ),
  6697. 'J' => array( 'Group' => 'Energy', 'Unit Name' => 'Joule', 'AllowPrefix' => True ),
  6698. 'e' => array( 'Group' => 'Energy', 'Unit Name' => 'Erg', 'AllowPrefix' => True ),
  6699. 'c' => array( 'Group' => 'Energy', 'Unit Name' => 'Thermodynamic calorie', 'AllowPrefix' => True ),
  6700. 'cal' => array( 'Group' => 'Energy', 'Unit Name' => 'IT calorie', 'AllowPrefix' => True ),
  6701. 'eV' => array( 'Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => True ),
  6702. 'ev' => array( 'Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => True ),
  6703. 'HPh' => array( 'Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => False ),
  6704. 'hh' => array( 'Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => False ),
  6705. 'Wh' => array( 'Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => True ),
  6706. 'wh' => array( 'Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => True ),
  6707. 'flb' => array( 'Group' => 'Energy', 'Unit Name' => 'Foot-pound', 'AllowPrefix' => False ),
  6708. 'BTU' => array( 'Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => False ),
  6709. 'btu' => array( 'Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => False ),
  6710. 'HP' => array( 'Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => False ),
  6711. 'h' => array( 'Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => False ),
  6712. 'W' => array( 'Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => True ),
  6713. 'w' => array( 'Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => True ),
  6714. 'T' => array( 'Group' => 'Magnetism', 'Unit Name' => 'Tesla', 'AllowPrefix' => True ),
  6715. 'ga' => array( 'Group' => 'Magnetism', 'Unit Name' => 'Gauss', 'AllowPrefix' => True ),
  6716. 'C' => array( 'Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => False ),
  6717. 'cel' => array( 'Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => False ),
  6718. 'F' => array( 'Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => False ),
  6719. 'fah' => array( 'Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => False ),
  6720. 'K' => array( 'Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => False ),
  6721. 'kel' => array( 'Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => False ),
  6722. 'tsp' => array( 'Group' => 'Liquid', 'Unit Name' => 'Teaspoon', 'AllowPrefix' => False ),
  6723. 'tbs' => array( 'Group' => 'Liquid', 'Unit Name' => 'Tablespoon', 'AllowPrefix' => False ),
  6724. 'oz' => array( 'Group' => 'Liquid', 'Unit Name' => 'Fluid Ounce', 'AllowPrefix' => False ),
  6725. 'cup' => array( 'Group' => 'Liquid', 'Unit Name' => 'Cup', 'AllowPrefix' => False ),
  6726. 'pt' => array( 'Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => False ),
  6727. 'us_pt' => array( 'Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => False ),
  6728. 'uk_pt' => array( 'Group' => 'Liquid', 'Unit Name' => 'U.K. Pint', 'AllowPrefix' => False ),
  6729. 'qt' => array( 'Group' => 'Liquid', 'Unit Name' => 'Quart', 'AllowPrefix' => False ),
  6730. 'gal' => array( 'Group' => 'Liquid', 'Unit Name' => 'Gallon', 'AllowPrefix' => False ),
  6731. 'l' => array( 'Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => True ),
  6732. 'lt' => array( 'Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => True )
  6733. );
  6734. private static $_conversionMultipliers = array( 'Y' => array( 'multiplier' => 1E24, 'name' => 'yotta' ),
  6735. 'Z' => array( 'multiplier' => 1E21, 'name' => 'zetta' ),
  6736. 'E' => array( 'multiplier' => 1E18, 'name' => 'exa' ),
  6737. 'P' => array( 'multiplier' => 1E15, 'name' => 'peta' ),
  6738. 'T' => array( 'multiplier' => 1E12, 'name' => 'tera' ),
  6739. 'G' => array( 'multiplier' => 1E9, 'name' => 'giga' ),
  6740. 'M' => array( 'multiplier' => 1E6, 'name' => 'mega' ),
  6741. 'k' => array( 'multiplier' => 1E3, 'name' => 'kilo' ),
  6742. 'h' => array( 'multiplier' => 1E2, 'name' => 'hecto' ),
  6743. 'e' => array( 'multiplier' => 1E1, 'name' => 'deka' ),
  6744. 'd' => array( 'multiplier' => 1E-1, 'name' => 'deci' ),
  6745. 'c' => array( 'multiplier' => 1E-2, 'name' => 'centi' ),
  6746. 'm' => array( 'multiplier' => 1E-3, 'name' => 'milli' ),
  6747. 'u' => array( 'multiplier' => 1E-6, 'name' => 'micro' ),
  6748. 'n' => array( 'multiplier' => 1E-9, 'name' => 'nano' ),
  6749. 'p' => array( 'multiplier' => 1E-12, 'name' => 'pico' ),
  6750. 'f' => array( 'multiplier' => 1E-15, 'name' => 'femto' ),
  6751. 'a' => array( 'multiplier' => 1E-18, 'name' => 'atto' ),
  6752. 'z' => array( 'multiplier' => 1E-21, 'name' => 'zepto' ),
  6753. 'y' => array( 'multiplier' => 1E-24, 'name' => 'yocto' )
  6754. );
  6755. private static $_unitConversions = array( 'Mass' => array( 'g' => array( 'g' => 1.0,
  6756. 'sg' => 6.85220500053478E-05,
  6757. 'lbm' => 2.20462291469134E-03,
  6758. 'u' => 6.02217000000000E+23,
  6759. 'ozm' => 3.52739718003627E-02
  6760. ),
  6761. 'sg' => array( 'g' => 1.45938424189287E+04,
  6762. 'sg' => 1.0,
  6763. 'lbm' => 3.21739194101647E+01,
  6764. 'u' => 8.78866000000000E+27,
  6765. 'ozm' => 5.14782785944229E+02
  6766. ),
  6767. 'lbm' => array( 'g' => 4.5359230974881148E+02,
  6768. 'sg' => 3.10810749306493E-02,
  6769. 'lbm' => 1.0,
  6770. 'u' => 2.73161000000000E+26,
  6771. 'ozm' => 1.60000023429410E+01
  6772. ),
  6773. 'u' => array( 'g' => 1.66053100460465E-24,
  6774. 'sg' => 1.13782988532950E-28,
  6775. 'lbm' => 3.66084470330684E-27,
  6776. 'u' => 1.0,
  6777. 'ozm' => 5.85735238300524E-26
  6778. ),
  6779. 'ozm' => array( 'g' => 2.83495152079732E+01,
  6780. 'sg' => 1.94256689870811E-03,
  6781. 'lbm' => 6.24999908478882E-02,
  6782. 'u' => 1.70725600000000E+25,
  6783. 'ozm' => 1.0
  6784. )
  6785. ),
  6786. 'Distance' => array( 'm' => array( 'm' => 1.0,
  6787. 'mi' => 6.21371192237334E-04,
  6788. 'Nmi' => 5.39956803455724E-04,
  6789. 'in' => 3.93700787401575E+01,
  6790. 'ft' => 3.28083989501312E+00,
  6791. 'yd' => 1.09361329797891E+00,
  6792. 'ang' => 1.00000000000000E+10,
  6793. 'Pica' => 2.83464566929116E+03
  6794. ),
  6795. 'mi' => array( 'm' => 1.60934400000000E+03,
  6796. 'mi' => 1.0,
  6797. 'Nmi' => 8.68976241900648E-01,
  6798. 'in' => 6.33600000000000E+04,
  6799. 'ft' => 5.28000000000000E+03,
  6800. 'yd' => 1.76000000000000E+03,
  6801. 'ang' => 1.60934400000000E+13,
  6802. 'Pica' => 4.56191999999971E+06
  6803. ),
  6804. 'Nmi' => array( 'm' => 1.85200000000000E+03,
  6805. 'mi' => 1.15077944802354E+00,
  6806. 'Nmi' => 1.0,
  6807. 'in' => 7.29133858267717E+04,
  6808. 'ft' => 6.07611548556430E+03,
  6809. 'yd' => 2.02537182785694E+03,
  6810. 'ang' => 1.85200000000000E+13,
  6811. 'Pica' => 5.24976377952723E+06
  6812. ),
  6813. 'in' => array( 'm' => 2.54000000000000E-02,
  6814. 'mi' => 1.57828282828283E-05,
  6815. 'Nmi' => 1.37149028077754E-05,
  6816. 'in' => 1.0,
  6817. 'ft' => 8.33333333333333E-02,
  6818. 'yd' => 2.77777777686643E-02,
  6819. 'ang' => 2.54000000000000E+08,
  6820. 'Pica' => 7.19999999999955E+01
  6821. ),
  6822. 'ft' => array( 'm' => 3.04800000000000E-01,
  6823. 'mi' => 1.89393939393939E-04,
  6824. 'Nmi' => 1.64578833693305E-04,
  6825. 'in' => 1.20000000000000E+01,
  6826. 'ft' => 1.0,
  6827. 'yd' => 3.33333333223972E-01,
  6828. 'ang' => 3.04800000000000E+09,
  6829. 'Pica' => 8.63999999999946E+02
  6830. ),
  6831. 'yd' => array( 'm' => 9.14400000300000E-01,
  6832. 'mi' => 5.68181818368230E-04,
  6833. 'Nmi' => 4.93736501241901E-04,
  6834. 'in' => 3.60000000118110E+01,
  6835. 'ft' => 3.00000000000000E+00,
  6836. 'yd' => 1.0,
  6837. 'ang' => 9.14400000300000E+09,
  6838. 'Pica' => 2.59200000085023E+03
  6839. ),
  6840. 'ang' => array( 'm' => 1.00000000000000E-10,
  6841. 'mi' => 6.21371192237334E-14,
  6842. 'Nmi' => 5.39956803455724E-14,
  6843. 'in' => 3.93700787401575E-09,
  6844. 'ft' => 3.28083989501312E-10,
  6845. 'yd' => 1.09361329797891E-10,
  6846. 'ang' => 1.0,
  6847. 'Pica' => 2.83464566929116E-07
  6848. ),
  6849. 'Pica' => array( 'm' => 3.52777777777800E-04,
  6850. 'mi' => 2.19205948372629E-07,
  6851. 'Nmi' => 1.90484761219114E-07,
  6852. 'in' => 1.38888888888898E-02,
  6853. 'ft' => 1.15740740740748E-03,
  6854. 'yd' => 3.85802469009251E-04,
  6855. 'ang' => 3.52777777777800E+06,
  6856. 'Pica' => 1.0
  6857. )
  6858. ),
  6859. 'Time' => array( 'yr' => array( 'yr' => 1.0,
  6860. 'day' => 365.25,
  6861. 'hr' => 8766.0,
  6862. 'mn' => 525960.0,
  6863. 'sec' => 31557600.0
  6864. ),
  6865. 'day' => array( 'yr' => 2.73785078713210E-03,
  6866. 'day' => 1.0,
  6867. 'hr' => 24.0,
  6868. 'mn' => 1440.0,
  6869. 'sec' => 86400.0
  6870. ),
  6871. 'hr' => array( 'yr' => 1.14077116130504E-04,
  6872. 'day' => 4.16666666666667E-02,
  6873. 'hr' => 1.0,
  6874. 'mn' => 60.0,
  6875. 'sec' => 3600.0
  6876. ),
  6877. 'mn' => array( 'yr' => 1.90128526884174E-06,
  6878. 'day' => 6.94444444444444E-04,
  6879. 'hr' => 1.66666666666667E-02,
  6880. 'mn' => 1.0,
  6881. 'sec' => 60.0
  6882. ),
  6883. 'sec' => array( 'yr' => 3.16880878140289E-08,
  6884. 'day' => 1.15740740740741E-05,
  6885. 'hr' => 2.77777777777778E-04,
  6886. 'mn' => 1.66666666666667E-02,
  6887. 'sec' => 1.0
  6888. )
  6889. ),
  6890. 'Pressure' => array( 'Pa' => array( 'Pa' => 1.0,
  6891. 'p' => 1.0,
  6892. 'atm' => 9.86923299998193E-06,
  6893. 'at' => 9.86923299998193E-06,
  6894. 'mmHg' => 7.50061707998627E-03
  6895. ),
  6896. 'p' => array( 'Pa' => 1.0,
  6897. 'p' => 1.0,
  6898. 'atm' => 9.86923299998193E-06,
  6899. 'at' => 9.86923299998193E-06,
  6900. 'mmHg' => 7.50061707998627E-03
  6901. ),
  6902. 'atm' => array( 'Pa' => 1.01324996583000E+05,
  6903. 'p' => 1.01324996583000E+05,
  6904. 'atm' => 1.0,
  6905. 'at' => 1.0,
  6906. 'mmHg' => 760.0
  6907. ),
  6908. 'at' => array( 'Pa' => 1.01324996583000E+05,
  6909. 'p' => 1.01324996583000E+05,
  6910. 'atm' => 1.0,
  6911. 'at' => 1.0,
  6912. 'mmHg' => 760.0
  6913. ),
  6914. 'mmHg' => array( 'Pa' => 1.33322363925000E+02,
  6915. 'p' => 1.33322363925000E+02,
  6916. 'atm' => 1.31578947368421E-03,
  6917. 'at' => 1.31578947368421E-03,
  6918. 'mmHg' => 1.0
  6919. )
  6920. ),
  6921. 'Force' => array( 'N' => array( 'N' => 1.0,
  6922. 'dyn' => 1.0E+5,
  6923. 'dy' => 1.0E+5,
  6924. 'lbf' => 2.24808923655339E-01
  6925. ),
  6926. 'dyn' => array( 'N' => 1.0E-5,
  6927. 'dyn' => 1.0,
  6928. 'dy' => 1.0,
  6929. 'lbf' => 2.24808923655339E-06
  6930. ),
  6931. 'dy' => array( 'N' => 1.0E-5,
  6932. 'dyn' => 1.0,
  6933. 'dy' => 1.0,
  6934. 'lbf' => 2.24808923655339E-06
  6935. ),
  6936. 'lbf' => array( 'N' => 4.448222,
  6937. 'dyn' => 4.448222E+5,
  6938. 'dy' => 4.448222E+5,
  6939. 'lbf' => 1.0
  6940. )
  6941. ),
  6942. 'Energy' => array( 'J' => array( 'J' => 1.0,
  6943. 'e' => 9.99999519343231E+06,
  6944. 'c' => 2.39006249473467E-01,
  6945. 'cal' => 2.38846190642017E-01,
  6946. 'eV' => 6.24145700000000E+18,
  6947. 'ev' => 6.24145700000000E+18,
  6948. 'HPh' => 3.72506430801000E-07,
  6949. 'hh' => 3.72506430801000E-07,
  6950. 'Wh' => 2.77777916238711E-04,
  6951. 'wh' => 2.77777916238711E-04,
  6952. 'flb' => 2.37304222192651E+01,
  6953. 'BTU' => 9.47815067349015E-04,
  6954. 'btu' => 9.47815067349015E-04
  6955. ),
  6956. 'e' => array( 'J' => 1.00000048065700E-07,
  6957. 'e' => 1.0,
  6958. 'c' => 2.39006364353494E-08,
  6959. 'cal' => 2.38846305445111E-08,
  6960. 'eV' => 6.24146000000000E+11,
  6961. 'ev' => 6.24146000000000E+11,
  6962. 'HPh' => 3.72506609848824E-14,
  6963. 'hh' => 3.72506609848824E-14,
  6964. 'Wh' => 2.77778049754611E-11,
  6965. 'wh' => 2.77778049754611E-11,
  6966. 'flb' => 2.37304336254586E-06,
  6967. 'BTU' => 9.47815522922962E-11,
  6968. 'btu' => 9.47815522922962E-11
  6969. ),
  6970. 'c' => array( 'J' => 4.18399101363672E+00,
  6971. 'e' => 4.18398900257312E+07,
  6972. 'c' => 1.0,
  6973. 'cal' => 9.99330315287563E-01,
  6974. 'eV' => 2.61142000000000E+19,
  6975. 'ev' => 2.61142000000000E+19,
  6976. 'HPh' => 1.55856355899327E-06,
  6977. 'hh' => 1.55856355899327E-06,
  6978. 'Wh' => 1.16222030532950E-03,
  6979. 'wh' => 1.16222030532950E-03,
  6980. 'flb' => 9.92878733152102E+01,
  6981. 'BTU' => 3.96564972437776E-03,
  6982. 'btu' => 3.96564972437776E-03
  6983. ),
  6984. 'cal' => array( 'J' => 4.18679484613929E+00,
  6985. 'e' => 4.18679283372801E+07,
  6986. 'c' => 1.00067013349059E+00,
  6987. 'cal' => 1.0,
  6988. 'eV' => 2.61317000000000E+19,
  6989. 'ev' => 2.61317000000000E+19,
  6990. 'HPh' => 1.55960800463137E-06,
  6991. 'hh' => 1.55960800463137E-06,
  6992. 'Wh' => 1.16299914807955E-03,
  6993. 'wh' => 1.16299914807955E-03,
  6994. 'flb' => 9.93544094443283E+01,
  6995. 'BTU' => 3.96830723907002E-03,
  6996. 'btu' => 3.96830723907002E-03
  6997. ),
  6998. 'eV' => array( 'J' => 1.60219000146921E-19,
  6999. 'e' => 1.60218923136574E-12,
  7000. 'c' => 3.82933423195043E-20,
  7001. 'cal' => 3.82676978535648E-20,
  7002. 'eV' => 1.0,
  7003. 'ev' => 1.0,
  7004. 'HPh' => 5.96826078912344E-26,
  7005. 'hh' => 5.96826078912344E-26,
  7006. 'Wh' => 4.45053000026614E-23,
  7007. 'wh' => 4.45053000026614E-23,
  7008. 'flb' => 3.80206452103492E-18,
  7009. 'BTU' => 1.51857982414846E-22,
  7010. 'btu' => 1.51857982414846E-22
  7011. ),
  7012. 'ev' => array( 'J' => 1.60219000146921E-19,
  7013. 'e' => 1.60218923136574E-12,
  7014. 'c' => 3.82933423195043E-20,
  7015. 'cal' => 3.82676978535648E-20,
  7016. 'eV' => 1.0,
  7017. 'ev' => 1.0,
  7018. 'HPh' => 5.96826078912344E-26,
  7019. 'hh' => 5.96826078912344E-26,
  7020. 'Wh' => 4.45053000026614E-23,
  7021. 'wh' => 4.45053000026614E-23,
  7022. 'flb' => 3.80206452103492E-18,
  7023. 'BTU' => 1.51857982414846E-22,
  7024. 'btu' => 1.51857982414846E-22
  7025. ),
  7026. 'HPh' => array( 'J' => 2.68451741316170E+06,
  7027. 'e' => 2.68451612283024E+13,
  7028. 'c' => 6.41616438565991E+05,
  7029. 'cal' => 6.41186757845835E+05,
  7030. 'eV' => 1.67553000000000E+25,
  7031. 'ev' => 1.67553000000000E+25,
  7032. 'HPh' => 1.0,
  7033. 'hh' => 1.0,
  7034. 'Wh' => 7.45699653134593E+02,
  7035. 'wh' => 7.45699653134593E+02,
  7036. 'flb' => 6.37047316692964E+07,
  7037. 'BTU' => 2.54442605275546E+03,
  7038. 'btu' => 2.54442605275546E+03
  7039. ),
  7040. 'hh' => array( 'J' => 2.68451741316170E+06,
  7041. 'e' => 2.68451612283024E+13,
  7042. 'c' => 6.41616438565991E+05,
  7043. 'cal' => 6.41186757845835E+05,
  7044. 'eV' => 1.67553000000000E+25,
  7045. 'ev' => 1.67553000000000E+25,
  7046. 'HPh' => 1.0,
  7047. 'hh' => 1.0,
  7048. 'Wh' => 7.45699653134593E+02,
  7049. 'wh' => 7.45699653134593E+02,
  7050. 'flb' => 6.37047316692964E+07,
  7051. 'BTU' => 2.54442605275546E+03,
  7052. 'btu' => 2.54442605275546E+03
  7053. ),
  7054. 'Wh' => array( 'J' => 3.59999820554720E+03,
  7055. 'e' => 3.59999647518369E+10,
  7056. 'c' => 8.60422069219046E+02,
  7057. 'cal' => 8.59845857713046E+02,
  7058. 'eV' => 2.24692340000000E+22,
  7059. 'ev' => 2.24692340000000E+22,
  7060. 'HPh' => 1.34102248243839E-03,
  7061. 'hh' => 1.34102248243839E-03,
  7062. 'Wh' => 1.0,
  7063. 'wh' => 1.0,
  7064. 'flb' => 8.54294774062316E+04,
  7065. 'BTU' => 3.41213254164705E+00,
  7066. 'btu' => 3.41213254164705E+00
  7067. ),
  7068. 'wh' => array( 'J' => 3.59999820554720E+03,
  7069. 'e' => 3.59999647518369E+10,
  7070. 'c' => 8.60422069219046E+02,
  7071. 'cal' => 8.59845857713046E+02,
  7072. 'eV' => 2.24692340000000E+22,
  7073. 'ev' => 2.24692340000000E+22,
  7074. 'HPh' => 1.34102248243839E-03,
  7075. 'hh' => 1.34102248243839E-03,
  7076. 'Wh' => 1.0,
  7077. 'wh' => 1.0,
  7078. 'flb' => 8.54294774062316E+04,
  7079. 'BTU' => 3.41213254164705E+00,
  7080. 'btu' => 3.41213254164705E+00
  7081. ),
  7082. 'flb' => array( 'J' => 4.21400003236424E-02,
  7083. 'e' => 4.21399800687660E+05,
  7084. 'c' => 1.00717234301644E-02,
  7085. 'cal' => 1.00649785509554E-02,
  7086. 'eV' => 2.63015000000000E+17,
  7087. 'ev' => 2.63015000000000E+17,
  7088. 'HPh' => 1.56974211145130E-08,
  7089. 'hh' => 1.56974211145130E-08,
  7090. 'Wh' => 1.17055614802000E-05,
  7091. 'wh' => 1.17055614802000E-05,
  7092. 'flb' => 1.0,
  7093. 'BTU' => 3.99409272448406E-05,
  7094. 'btu' => 3.99409272448406E-05
  7095. ),
  7096. 'BTU' => array( 'J' => 1.05505813786749E+03,
  7097. 'e' => 1.05505763074665E+10,
  7098. 'c' => 2.52165488508168E+02,
  7099. 'cal' => 2.51996617135510E+02,
  7100. 'eV' => 6.58510000000000E+21,
  7101. 'ev' => 6.58510000000000E+21,
  7102. 'HPh' => 3.93015941224568E-04,
  7103. 'hh' => 3.93015941224568E-04,
  7104. 'Wh' => 2.93071851047526E-01,
  7105. 'wh' => 2.93071851047526E-01,
  7106. 'flb' => 2.50369750774671E+04,
  7107. 'BTU' => 1.0,
  7108. 'btu' => 1.0,
  7109. ),
  7110. 'btu' => array( 'J' => 1.05505813786749E+03,
  7111. 'e' => 1.05505763074665E+10,
  7112. 'c' => 2.52165488508168E+02,
  7113. 'cal' => 2.51996617135510E+02,
  7114. 'eV' => 6.58510000000000E+21,
  7115. 'ev' => 6.58510000000000E+21,
  7116. 'HPh' => 3.93015941224568E-04,
  7117. 'hh' => 3.93015941224568E-04,
  7118. 'Wh' => 2.93071851047526E-01,
  7119. 'wh' => 2.93071851047526E-01,
  7120. 'flb' => 2.50369750774671E+04,
  7121. 'BTU' => 1.0,
  7122. 'btu' => 1.0,
  7123. )
  7124. ),
  7125. 'Power' => array( 'HP' => array( 'HP' => 1.0,
  7126. 'h' => 1.0,
  7127. 'W' => 7.45701000000000E+02,
  7128. 'w' => 7.45701000000000E+02
  7129. ),
  7130. 'h' => array( 'HP' => 1.0,
  7131. 'h' => 1.0,
  7132. 'W' => 7.45701000000000E+02,
  7133. 'w' => 7.45701000000000E+02
  7134. ),
  7135. 'W' => array( 'HP' => 1.34102006031908E-03,
  7136. 'h' => 1.34102006031908E-03,
  7137. 'W' => 1.0,
  7138. 'w' => 1.0
  7139. ),
  7140. 'w' => array( 'HP' => 1.34102006031908E-03,
  7141. 'h' => 1.34102006031908E-03,
  7142. 'W' => 1.0,
  7143. 'w' => 1.0
  7144. )
  7145. ),
  7146. 'Magnetism' => array( 'T' => array( 'T' => 1.0,
  7147. 'ga' => 10000.0
  7148. ),
  7149. 'ga' => array( 'T' => 0.0001,
  7150. 'ga' => 1.0
  7151. )
  7152. ),
  7153. 'Liquid' => array( 'tsp' => array( 'tsp' => 1.0,
  7154. 'tbs' => 3.33333333333333E-01,
  7155. 'oz' => 1.66666666666667E-01,
  7156. 'cup' => 2.08333333333333E-02,
  7157. 'pt' => 1.04166666666667E-02,
  7158. 'us_pt' => 1.04166666666667E-02,
  7159. 'uk_pt' => 8.67558516821960E-03,
  7160. 'qt' => 5.20833333333333E-03,
  7161. 'gal' => 1.30208333333333E-03,
  7162. 'l' => 4.92999408400710E-03,
  7163. 'lt' => 4.92999408400710E-03
  7164. ),
  7165. 'tbs' => array( 'tsp' => 3.00000000000000E+00,
  7166. 'tbs' => 1.0,
  7167. 'oz' => 5.00000000000000E-01,
  7168. 'cup' => 6.25000000000000E-02,
  7169. 'pt' => 3.12500000000000E-02,
  7170. 'us_pt' => 3.12500000000000E-02,
  7171. 'uk_pt' => 2.60267555046588E-02,
  7172. 'qt' => 1.56250000000000E-02,
  7173. 'gal' => 3.90625000000000E-03,
  7174. 'l' => 1.47899822520213E-02,
  7175. 'lt' => 1.47899822520213E-02
  7176. ),
  7177. 'oz' => array( 'tsp' => 6.00000000000000E+00,
  7178. 'tbs' => 2.00000000000000E+00,
  7179. 'oz' => 1.0,
  7180. 'cup' => 1.25000000000000E-01,
  7181. 'pt' => 6.25000000000000E-02,
  7182. 'us_pt' => 6.25000000000000E-02,
  7183. 'uk_pt' => 5.20535110093176E-02,
  7184. 'qt' => 3.12500000000000E-02,
  7185. 'gal' => 7.81250000000000E-03,
  7186. 'l' => 2.95799645040426E-02,
  7187. 'lt' => 2.95799645040426E-02
  7188. ),
  7189. 'cup' => array( 'tsp' => 4.80000000000000E+01,
  7190. 'tbs' => 1.60000000000000E+01,
  7191. 'oz' => 8.00000000000000E+00,
  7192. 'cup' => 1.0,
  7193. 'pt' => 5.00000000000000E-01,
  7194. 'us_pt' => 5.00000000000000E-01,
  7195. 'uk_pt' => 4.16428088074541E-01,
  7196. 'qt' => 2.50000000000000E-01,
  7197. 'gal' => 6.25000000000000E-02,
  7198. 'l' => 2.36639716032341E-01,
  7199. 'lt' => 2.36639716032341E-01
  7200. ),
  7201. 'pt' => array( 'tsp' => 9.60000000000000E+01,
  7202. 'tbs' => 3.20000000000000E+01,
  7203. 'oz' => 1.60000000000000E+01,
  7204. 'cup' => 2.00000000000000E+00,
  7205. 'pt' => 1.0,
  7206. 'us_pt' => 1.0,
  7207. 'uk_pt' => 8.32856176149081E-01,
  7208. 'qt' => 5.00000000000000E-01,
  7209. 'gal' => 1.25000000000000E-01,
  7210. 'l' => 4.73279432064682E-01,
  7211. 'lt' => 4.73279432064682E-01
  7212. ),
  7213. 'us_pt' => array( 'tsp' => 9.60000000000000E+01,
  7214. 'tbs' => 3.20000000000000E+01,
  7215. 'oz' => 1.60000000000000E+01,
  7216. 'cup' => 2.00000000000000E+00,
  7217. 'pt' => 1.0,
  7218. 'us_pt' => 1.0,
  7219. 'uk_pt' => 8.32856176149081E-01,
  7220. 'qt' => 5.00000000000000E-01,
  7221. 'gal' => 1.25000000000000E-01,
  7222. 'l' => 4.73279432064682E-01,
  7223. 'lt' => 4.73279432064682E-01
  7224. ),
  7225. 'uk_pt' => array( 'tsp' => 1.15266000000000E+02,
  7226. 'tbs' => 3.84220000000000E+01,
  7227. 'oz' => 1.92110000000000E+01,
  7228. 'cup' => 2.40137500000000E+00,
  7229. 'pt' => 1.20068750000000E+00,
  7230. 'us_pt' => 1.20068750000000E+00,
  7231. 'uk_pt' => 1.0,
  7232. 'qt' => 6.00343750000000E-01,
  7233. 'gal' => 1.50085937500000E-01,
  7234. 'l' => 5.68260698087162E-01,
  7235. 'lt' => 5.68260698087162E-01
  7236. ),
  7237. 'qt' => array( 'tsp' => 1.92000000000000E+02,
  7238. 'tbs' => 6.40000000000000E+01,
  7239. 'oz' => 3.20000000000000E+01,
  7240. 'cup' => 4.00000000000000E+00,
  7241. 'pt' => 2.00000000000000E+00,
  7242. 'us_pt' => 2.00000000000000E+00,
  7243. 'uk_pt' => 1.66571235229816E+00,
  7244. 'qt' => 1.0,
  7245. 'gal' => 2.50000000000000E-01,
  7246. 'l' => 9.46558864129363E-01,
  7247. 'lt' => 9.46558864129363E-01
  7248. ),
  7249. 'gal' => array( 'tsp' => 7.68000000000000E+02,
  7250. 'tbs' => 2.56000000000000E+02,
  7251. 'oz' => 1.28000000000000E+02,
  7252. 'cup' => 1.60000000000000E+01,
  7253. 'pt' => 8.00000000000000E+00,
  7254. 'us_pt' => 8.00000000000000E+00,
  7255. 'uk_pt' => 6.66284940919265E+00,
  7256. 'qt' => 4.00000000000000E+00,
  7257. 'gal' => 1.0,
  7258. 'l' => 3.78623545651745E+00,
  7259. 'lt' => 3.78623545651745E+00
  7260. ),
  7261. 'l' => array( 'tsp' => 2.02840000000000E+02,
  7262. 'tbs' => 6.76133333333333E+01,
  7263. 'oz' => 3.38066666666667E+01,
  7264. 'cup' => 4.22583333333333E+00,
  7265. 'pt' => 2.11291666666667E+00,
  7266. 'us_pt' => 2.11291666666667E+00,
  7267. 'uk_pt' => 1.75975569552166E+00,
  7268. 'qt' => 1.05645833333333E+00,
  7269. 'gal' => 2.64114583333333E-01,
  7270. 'l' => 1.0,
  7271. 'lt' => 1.0
  7272. ),
  7273. 'lt' => array( 'tsp' => 2.02840000000000E+02,
  7274. 'tbs' => 6.76133333333333E+01,
  7275. 'oz' => 3.38066666666667E+01,
  7276. 'cup' => 4.22583333333333E+00,
  7277. 'pt' => 2.11291666666667E+00,
  7278. 'us_pt' => 2.11291666666667E+00,
  7279. 'uk_pt' => 1.75975569552166E+00,
  7280. 'qt' => 1.05645833333333E+00,
  7281. 'gal' => 2.64114583333333E-01,
  7282. 'l' => 1.0,
  7283. 'lt' => 1.0
  7284. )
  7285. )
  7286. );
  7287. /**
  7288. * getConversionGroups
  7289. *
  7290. * @return array
  7291. */
  7292. public static function getConversionGroups() {
  7293. $conversionGroups = array();
  7294. foreach(self::$_conversionUnits as $conversionUnit) {
  7295. $conversionGroups[] = $conversionUnit['Group'];
  7296. }
  7297. return array_merge(array_unique($conversionGroups));
  7298. } // function getConversionGroups()
  7299. /**
  7300. * getConversionGroupUnits
  7301. *
  7302. * @return array
  7303. */
  7304. public static function getConversionGroupUnits($group = NULL) {
  7305. $conversionGroups = array();
  7306. foreach(self::$_conversionUnits as $conversionUnit => $conversionGroup) {
  7307. if ((is_null($group)) || ($conversionGroup['Group'] == $group)) {
  7308. $conversionGroups[$conversionGroup['Group']][] = $conversionUnit;
  7309. }
  7310. }
  7311. return $conversionGroups;
  7312. } // function getConversionGroupUnits()
  7313. /**
  7314. * getConversionGroupUnitDetails
  7315. *
  7316. * @return array
  7317. */
  7318. public static function getConversionGroupUnitDetails($group = NULL) {
  7319. $conversionGroups = array();
  7320. foreach(self::$_conversionUnits as $conversionUnit => $conversionGroup) {
  7321. if ((is_null($group)) || ($conversionGroup['Group'] == $group)) {
  7322. $conversionGroups[$conversionGroup['Group']][] = array( 'unit' => $conversionUnit,
  7323. 'description' => $conversionGroup['Unit Name']
  7324. );
  7325. }
  7326. }
  7327. return $conversionGroups;
  7328. } // function getConversionGroupUnitDetails()
  7329. /**
  7330. * getConversionGroups
  7331. *
  7332. * @return array
  7333. */
  7334. public static function getConversionMultipliers() {
  7335. return self::$_conversionMultipliers;
  7336. } // function getConversionGroups()
  7337. /**
  7338. * CONVERTUOM
  7339. *
  7340. * @param float $value
  7341. * @param string $fromUOM
  7342. * @param string $toUOM
  7343. * @return float
  7344. */
  7345. public static function CONVERTUOM($value, $fromUOM, $toUOM) {
  7346. $value = self::flattenSingleValue($value);
  7347. $fromUOM = self::flattenSingleValue($fromUOM);
  7348. $toUOM = self::flattenSingleValue($toUOM);
  7349. if (!is_numeric($value)) {
  7350. return self::$_errorCodes['value'];
  7351. }
  7352. $fromMultiplier = 1;
  7353. if (isset(self::$_conversionUnits[$fromUOM])) {
  7354. $unitGroup1 = self::$_conversionUnits[$fromUOM]['Group'];
  7355. } else {
  7356. $fromMultiplier = substr($fromUOM,0,1);
  7357. $fromUOM = substr($fromUOM,1);
  7358. if (isset(self::$_conversionMultipliers[$fromMultiplier])) {
  7359. $fromMultiplier = self::$_conversionMultipliers[$fromMultiplier]['multiplier'];
  7360. } else {
  7361. return self::$_errorCodes['na'];
  7362. }
  7363. if ((isset(self::$_conversionUnits[$fromUOM])) && (self::$_conversionUnits[$fromUOM]['AllowPrefix'])) {
  7364. $unitGroup1 = self::$_conversionUnits[$fromUOM]['Group'];
  7365. } else {
  7366. return self::$_errorCodes['na'];
  7367. }
  7368. }
  7369. $value *= $fromMultiplier;
  7370. $toMultiplier = 1;
  7371. if (isset(self::$_conversionUnits[$toUOM])) {
  7372. $unitGroup2 = self::$_conversionUnits[$toUOM]['Group'];
  7373. } else {
  7374. $toMultiplier = substr($toUOM,0,1);
  7375. $toUOM = substr($toUOM,1);
  7376. if (isset(self::$_conversionMultipliers[$toMultiplier])) {
  7377. $toMultiplier = self::$_conversionMultipliers[$toMultiplier]['multiplier'];
  7378. } else {
  7379. return self::$_errorCodes['na'];
  7380. }
  7381. if ((isset(self::$_conversionUnits[$toUOM])) && (self::$_conversionUnits[$toUOM]['AllowPrefix'])) {
  7382. $unitGroup2 = self::$_conversionUnits[$toUOM]['Group'];
  7383. } else {
  7384. return self::$_errorCodes['na'];
  7385. }
  7386. }
  7387. if ($unitGroup1 != $unitGroup2) {
  7388. return self::$_errorCodes['na'];
  7389. }
  7390. if ($fromUOM == $toUOM) {
  7391. return 1.0;
  7392. } elseif ($unitGroup1 == 'Temperature') {
  7393. if (($fromUOM == 'F') || ($fromUOM == 'fah')) {
  7394. if (($toUOM == 'F') || ($toUOM == 'fah')) {
  7395. return 1.0;
  7396. } else {
  7397. $value = (($value - 32) / 1.8);
  7398. if (($toUOM == 'K') || ($toUOM == 'kel')) {
  7399. $value += 273.15;
  7400. }
  7401. return $value;
  7402. }
  7403. } elseif ((($fromUOM == 'K') || ($fromUOM == 'kel')) &&
  7404. (($toUOM == 'K') || ($toUOM == 'kel'))) {
  7405. return 1.0;
  7406. } elseif ((($fromUOM == 'C') || ($fromUOM == 'cel')) &&
  7407. (($toUOM == 'C') || ($toUOM == 'cel'))) {
  7408. return 1.0;
  7409. }
  7410. if (($toUOM == 'F') || ($toUOM == 'fah')) {
  7411. if (($fromUOM == 'K') || ($fromUOM == 'kel')) {
  7412. $value -= 273.15;
  7413. }
  7414. return ($value * 1.8) + 32;
  7415. }
  7416. if (($toUOM == 'C') || ($toUOM == 'cel')) {
  7417. return $value - 273.15;
  7418. }
  7419. return $value + 273.15;
  7420. }
  7421. return ($value * self::$_unitConversions[$unitGroup1][$fromUOM][$toUOM]) / $toMultiplier;
  7422. } // function CONVERTUOM()
  7423. /**
  7424. * BESSELI
  7425. *
  7426. * Returns the modified Bessel function, which is equivalent to the Bessel function evaluated for purely imaginary arguments
  7427. *
  7428. * @param float $x
  7429. * @param float $n
  7430. * @return int
  7431. */
  7432. public static function BESSELI($x, $n) {
  7433. $x = self::flattenSingleValue($x);
  7434. $n = floor(self::flattenSingleValue($n));
  7435. if ((is_numeric($x)) && (is_numeric($n))) {
  7436. if ($n < 0) {
  7437. return self::$_errorCodes['num'];
  7438. }
  7439. $f_2_PI = 2 * pi();
  7440. if (abs($x) <= 30) {
  7441. $fTerm = pow($x / 2, $n) / self::FACT($n);
  7442. $nK = 1;
  7443. $fResult = $fTerm;
  7444. $fSqrX = ($x * $x) / 4;
  7445. do {
  7446. $fTerm *= $fSqrX;
  7447. $fTerm /= ($nK * ($nK + $n));
  7448. $fResult += $fTerm;
  7449. } while ((abs($fTerm) > 1e-10) && (++$nK < 100));
  7450. } else {
  7451. $fXAbs = abs($x);
  7452. $fResult = exp($fXAbs) / sqrt($f_2_PI * $fXAbs);
  7453. if (($n && 1) && ($x < 0)) {
  7454. $fResult = -$fResult;
  7455. }
  7456. }
  7457. return $fResult;
  7458. }
  7459. return self::$_errorCodes['value'];
  7460. } // function BESSELI()
  7461. /**
  7462. * BESSELJ
  7463. *
  7464. * Returns the Bessel function
  7465. *
  7466. * @param float $x
  7467. * @param float $n
  7468. * @return int
  7469. */
  7470. public static function BESSELJ($x, $n) {
  7471. $x = self::flattenSingleValue($x);
  7472. $n = floor(self::flattenSingleValue($n));
  7473. if ((is_numeric($x)) && (is_numeric($n))) {
  7474. if ($n < 0) {
  7475. return self::$_errorCodes['num'];
  7476. }
  7477. $f_PI_DIV_2 = M_PI / 2;
  7478. $f_PI_DIV_4 = M_PI / 4;
  7479. $fResult = 0;
  7480. if (abs($x) <= 30) {
  7481. $fTerm = pow($x / 2, $n) / self::FACT($n);
  7482. $nK = 1;
  7483. $fResult = $fTerm;
  7484. $fSqrX = ($x * $x) / -4;
  7485. do {
  7486. $fTerm *= $fSqrX;
  7487. $fTerm /= ($nK * ($nK + $n));
  7488. $fResult += $fTerm;
  7489. } while ((abs($fTerm) > 1e-10) && (++$nK < 100));
  7490. } else {
  7491. $fXAbs = abs($x);
  7492. $fResult = sqrt(M_2DIVPI / $fXAbs) * cos($fXAbs - $n * $f_PI_DIV_2 - $f_PI_DIV_4);
  7493. if (($n && 1) && ($x < 0)) {
  7494. $fResult = -$fResult;
  7495. }
  7496. }
  7497. return $fResult;
  7498. }
  7499. return self::$_errorCodes['value'];
  7500. } // function BESSELJ()
  7501. private static function _Besselk0($fNum) {
  7502. if ($fNum <= 2) {
  7503. $fNum2 = $fNum * 0.5;
  7504. $y = ($fNum2 * $fNum2);
  7505. $fRet = -log($fNum2) * self::BESSELI($fNum, 0) +
  7506. (-0.57721566 + $y * (0.42278420 + $y * (0.23069756 + $y * (0.3488590e-1 + $y * (0.262698e-2 + $y *
  7507. (0.10750e-3 + $y * 0.74e-5))))));
  7508. } else {
  7509. $y = 2 / $fNum;
  7510. $fRet = exp(-$fNum) / sqrt($fNum) *
  7511. (1.25331414 + $y * (-0.7832358e-1 + $y * (0.2189568e-1 + $y * (-0.1062446e-1 + $y *
  7512. (0.587872e-2 + $y * (-0.251540e-2 + $y * 0.53208e-3))))));
  7513. }
  7514. return $fRet;
  7515. } // function _Besselk0()
  7516. private static function _Besselk1($fNum) {
  7517. if ($fNum <= 2) {
  7518. $fNum2 = $fNum * 0.5;
  7519. $y = ($fNum2 * $fNum2);
  7520. $fRet = log($fNum2) * self::BESSELI($fNum, 1) +
  7521. (1 + $y * (0.15443144 + $y * (-0.67278579 + $y * (-0.18156897 + $y * (-0.1919402e-1 + $y *
  7522. (-0.110404e-2 + $y * (-0.4686e-4))))))) / $fNum;
  7523. } else {
  7524. $y = 2 / $fNum;
  7525. $fRet = exp(-$fNum) / sqrt($fNum) *
  7526. (1.25331414 + $y * (0.23498619 + $y * (-0.3655620e-1 + $y * (0.1504268e-1 + $y * (-0.780353e-2 + $y *
  7527. (0.325614e-2 + $y * (-0.68245e-3)))))));
  7528. }
  7529. return $fRet;
  7530. } // function _Besselk1()
  7531. /**
  7532. * BESSELK
  7533. *
  7534. * Returns the modified Bessel function, which is equivalent to the Bessel functions evaluated for purely imaginary arguments.
  7535. *
  7536. * @param float $x
  7537. * @param float $ord
  7538. * @return float
  7539. */
  7540. public static function BESSELK($x, $ord) {
  7541. $x = self::flattenSingleValue($x);
  7542. $ord = floor(self::flattenSingleValue($ord));
  7543. if ((is_numeric($x)) && (is_numeric($ord))) {
  7544. if ($ord < 0) {
  7545. return self::$_errorCodes['num'];
  7546. }
  7547. switch($ord) {
  7548. case 0 : return self::_Besselk0($x);
  7549. break;
  7550. case 1 : return self::_Besselk1($x);
  7551. break;
  7552. default : $fTox = 2 / $x;
  7553. $fBkm = self::_Besselk0($x);
  7554. $fBk = self::_Besselk1($x);
  7555. for ($n = 1; $n < $ord; ++$n) {
  7556. $fBkp = $fBkm + $n * $fTox * $fBk;
  7557. $fBkm = $fBk;
  7558. $fBk = $fBkp;
  7559. }
  7560. }
  7561. return $fBk;
  7562. }
  7563. return self::$_errorCodes['value'];
  7564. } // function BESSELK()
  7565. private static function _Bessely0($fNum) {
  7566. if ($fNum < 8.0) {
  7567. $y = ($fNum * $fNum);
  7568. $f1 = -2957821389.0 + $y * (7062834065.0 + $y * (-512359803.6 + $y * (10879881.29 + $y * (-86327.92757 + $y * 228.4622733))));
  7569. $f2 = 40076544269.0 + $y * (745249964.8 + $y * (7189466.438 + $y * (47447.26470 + $y * (226.1030244 + $y))));
  7570. $fRet = $f1 / $f2 + M_2DIVPI * self::BESSELJ($fNum, 0) * log($fNum);
  7571. } else {
  7572. $z = 8.0 / $fNum;
  7573. $y = ($z * $z);
  7574. $xx = $fNum - 0.785398164;
  7575. $f1 = 1 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6)));
  7576. $f2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 + $y * (-0.934945152e-7))));
  7577. $fRet = sqrt(M_2DIVPI / $fNum) * (sin($xx) * $f1 + $z * cos($xx) * $f2);
  7578. }
  7579. return $fRet;
  7580. } // function _Bessely0()
  7581. private static function _Bessely1($fNum) {
  7582. if ($fNum < 8.0) {
  7583. $y = ($fNum * $fNum);
  7584. $f1 = $fNum * (-0.4900604943e13 + $y * (0.1275274390e13 + $y * (-0.5153438139e11 + $y * (0.7349264551e9 + $y *
  7585. (-0.4237922726e7 + $y * 0.8511937935e4)))));
  7586. $f2 = 0.2499580570e14 + $y * (0.4244419664e12 + $y * (0.3733650367e10 + $y * (0.2245904002e8 + $y *
  7587. (0.1020426050e6 + $y * (0.3549632885e3 + $y)))));
  7588. $fRet = $f1 / $f2 + M_2DIVPI * ( self::BESSELJ($fNum, 1) * log($fNum) - 1 / $fNum);
  7589. } else {
  7590. $z = 8.0 / $fNum;
  7591. $y = ($z * $z);
  7592. $xx = $fNum - 2.356194491;
  7593. $f1 = 1 + $y * (0.183105e-2 + $y * (-0.3516396496e-4 + $y * (0.2457520174e-5 + $y * (-0.240337019e6))));
  7594. $f2 = 0.04687499995 + $y * (-0.2002690873e-3 + $y * (0.8449199096e-5 + $y * (-0.88228987e-6 + $y * 0.105787412e-6)));
  7595. $fRet = sqrt(M_2DIVPI / $fNum) * (sin($xx) * $f1 + $z * cos($xx) * $f2);
  7596. #i12430# ...but this seems to work much better.
  7597. // $fRet = sqrt(M_2DIVPI / $fNum) * sin($fNum - 2.356194491);
  7598. }
  7599. return $fRet;
  7600. } // function _Bessely1()
  7601. /**
  7602. * BESSELY
  7603. *
  7604. * Returns the Bessel function, which is also called the Weber function or the Neumann function.
  7605. *
  7606. * @param float $x
  7607. * @param float $n
  7608. * @return int
  7609. */
  7610. public static function BESSELY($x, $ord) {
  7611. $x = self::flattenSingleValue($x);
  7612. $ord = floor(self::flattenSingleValue($ord));
  7613. if ((is_numeric($x)) && (is_numeric($ord))) {
  7614. if ($ord < 0) {
  7615. return self::$_errorCodes['num'];
  7616. }
  7617. switch($ord) {
  7618. case 0 : return self::_Bessely0($x);
  7619. break;
  7620. case 1 : return self::_Bessely1($x);
  7621. break;
  7622. default: $fTox = 2 / $x;
  7623. $fBym = self::_Bessely0($x);
  7624. $fBy = self::_Bessely1($x);
  7625. for ($n = 1; $n < $ord; ++$n) {
  7626. $fByp = $n * $fTox * $fBy - $fBym;
  7627. $fBym = $fBy;
  7628. $fBy = $fByp;
  7629. }
  7630. }
  7631. return $fBy;
  7632. }
  7633. return self::$_errorCodes['value'];
  7634. } // function BESSELY()
  7635. /**
  7636. * DELTA
  7637. *
  7638. * Tests whether two values are equal. Returns 1 if number1 = number2; returns 0 otherwise.
  7639. *
  7640. * @param float $a
  7641. * @param float $b
  7642. * @return int
  7643. */
  7644. public static function DELTA($a, $b=0) {
  7645. $a = self::flattenSingleValue($a);
  7646. $b = self::flattenSingleValue($b);
  7647. return (int) ($a == $b);
  7648. } // function DELTA()
  7649. /**
  7650. * GESTEP
  7651. *
  7652. * Returns 1 if number = step; returns 0 (zero) otherwise
  7653. *
  7654. * @param float $number
  7655. * @param float $step
  7656. * @return int
  7657. */
  7658. public static function GESTEP($number, $step=0) {
  7659. $number = self::flattenSingleValue($number);
  7660. $step = self::flattenSingleValue($step);
  7661. return (int) ($number >= $step);
  7662. } // function GESTEP()
  7663. //
  7664. // Private method to calculate the erf value
  7665. //
  7666. private static $_two_sqrtpi = 1.128379167095512574;
  7667. private static function _erfVal($x) {
  7668. if (abs($x) > 2.2) {
  7669. return 1 - self::_erfcVal($x);
  7670. }
  7671. $sum = $term = $x;
  7672. $xsqr = ($x * $x);
  7673. $j = 1;
  7674. do {
  7675. $term *= $xsqr / $j;
  7676. $sum -= $term / (2 * $j + 1);
  7677. ++$j;
  7678. $term *= $xsqr / $j;
  7679. $sum += $term / (2 * $j + 1);
  7680. ++$j;
  7681. if ($sum == 0.0) {
  7682. break;
  7683. }
  7684. } while (abs($term / $sum) > PRECISION);
  7685. return self::$_two_sqrtpi * $sum;
  7686. } // function _erfVal()
  7687. /**
  7688. * ERF
  7689. *
  7690. * Returns the error function integrated between lower_limit and upper_limit
  7691. *
  7692. * @param float $lower lower bound for integrating ERF
  7693. * @param float $upper upper bound for integrating ERF.
  7694. * If omitted, ERF integrates between zero and lower_limit
  7695. * @return int
  7696. */
  7697. public static function ERF($lower, $upper = null) {
  7698. $lower = self::flattenSingleValue($lower);
  7699. $upper = self::flattenSingleValue($upper);
  7700. if (is_numeric($lower)) {
  7701. if ($lower < 0) {
  7702. return self::$_errorCodes['num'];
  7703. }
  7704. if (is_null($upper)) {
  7705. return self::_erfVal($lower);
  7706. }
  7707. if (is_numeric($upper)) {
  7708. if ($upper < 0) {
  7709. return self::$_errorCodes['num'];
  7710. }
  7711. return self::_erfVal($upper) - self::_erfVal($lower);
  7712. }
  7713. }
  7714. return self::$_errorCodes['value'];
  7715. } // function ERF()
  7716. //
  7717. // Private method to calculate the erfc value
  7718. //
  7719. private static $_one_sqrtpi = 0.564189583547756287;
  7720. private static function _erfcVal($x) {
  7721. if (abs($x) < 2.2) {
  7722. return 1 - self::_erfVal($x);
  7723. }
  7724. if ($x < 0) {
  7725. return 2 - self::erfc(-$x);
  7726. }
  7727. $a = $n = 1;
  7728. $b = $c = $x;
  7729. $d = ($x * $x) + 0.5;
  7730. $q1 = $q2 = $b / $d;
  7731. $t = 0;
  7732. do {
  7733. $t = $a * $n + $b * $x;
  7734. $a = $b;
  7735. $b = $t;
  7736. $t = $c * $n + $d * $x;
  7737. $c = $d;
  7738. $d = $t;
  7739. $n += 0.5;
  7740. $q1 = $q2;
  7741. $q2 = $b / $d;
  7742. } while ((abs($q1 - $q2) / $q2) > PRECISION);
  7743. return self::$_one_sqrtpi * exp(-$x * $x) * $q2;
  7744. } // function _erfcVal()
  7745. /**
  7746. * ERFC
  7747. *
  7748. * Returns the complementary ERF function integrated between x and infinity
  7749. *
  7750. * @param float $x The lower bound for integrating ERF
  7751. * @return int
  7752. */
  7753. public static function ERFC($x) {
  7754. $x = self::flattenSingleValue($x);
  7755. if (is_numeric($x)) {
  7756. if ($x < 0) {
  7757. return self::$_errorCodes['num'];
  7758. }
  7759. return self::_erfcVal($x);
  7760. }
  7761. return self::$_errorCodes['value'];
  7762. } // function ERFC()
  7763. /**
  7764. * LOWERCASE
  7765. *
  7766. * Converts a string value to upper case.
  7767. *
  7768. * @param string $mixedCaseString
  7769. * @return string
  7770. */
  7771. public static function LOWERCASE($mixedCaseString) {
  7772. $mixedCaseString = self::flattenSingleValue($mixedCaseString);
  7773. if (is_bool($mixedCaseString)) {
  7774. $mixedCaseString = ($mixedCaseString) ? 'TRUE' : 'FALSE';
  7775. }
  7776. if (function_exists('mb_convert_case')) {
  7777. return mb_convert_case($mixedCaseString, MB_CASE_LOWER, 'UTF-8');
  7778. } else {
  7779. return strtoupper($mixedCaseString);
  7780. }
  7781. } // function LOWERCASE()
  7782. /**
  7783. * UPPERCASE
  7784. *
  7785. * Converts a string value to upper case.
  7786. *
  7787. * @param string $mixedCaseString
  7788. * @return string
  7789. */
  7790. public static function UPPERCASE($mixedCaseString) {
  7791. $mixedCaseString = self::flattenSingleValue($mixedCaseString);
  7792. if (is_bool($mixedCaseString)) {
  7793. $mixedCaseString = ($mixedCaseString) ? 'TRUE' : 'FALSE';
  7794. }
  7795. if (function_exists('mb_convert_case')) {
  7796. return mb_convert_case($mixedCaseString, MB_CASE_UPPER, 'UTF-8');
  7797. } else {
  7798. return strtoupper($mixedCaseString);
  7799. }
  7800. } // function UPPERCASE()
  7801. /**
  7802. * PROPERCASE
  7803. *
  7804. * Converts a string value to upper case.
  7805. *
  7806. * @param string $mixedCaseString
  7807. * @return string
  7808. */
  7809. public static function PROPERCASE($mixedCaseString) {
  7810. $mixedCaseString = self::flattenSingleValue($mixedCaseString);
  7811. if (is_bool($mixedCaseString)) {
  7812. $mixedCaseString = ($mixedCaseString) ? 'TRUE' : 'FALSE';
  7813. }
  7814. if (function_exists('mb_convert_case')) {
  7815. return mb_convert_case($mixedCaseString, MB_CASE_TITLE, 'UTF-8');
  7816. } else {
  7817. return ucwords($mixedCaseString);
  7818. }
  7819. } // function PROPERCASE()
  7820. /**
  7821. * DOLLAR
  7822. *
  7823. * This function converts a number to text using currency format, with the decimals rounded to the specified place.
  7824. * The format used is $#,##0.00_);($#,##0.00)..
  7825. *
  7826. * @param float $value The value to format
  7827. * @param int $decimals The number of digits to display to the right of the decimal point.
  7828. * If decimals is negative, number is rounded to the left of the decimal point.
  7829. * If you omit decimals, it is assumed to be 2
  7830. * @return string
  7831. */
  7832. public static function DOLLAR($value = 0, $decimals = 2) {
  7833. $value = self::flattenSingleValue($value);
  7834. $decimals = is_null($decimals) ? 0 : self::flattenSingleValue($decimals);
  7835. // Validate parameters
  7836. if (!is_numeric($value) || !is_numeric($decimals)) {
  7837. return self::$_errorCodes['num'];
  7838. }
  7839. $decimals = floor($decimals);
  7840. if ($decimals > 0) {
  7841. return money_format('%.'.$decimals.'n',$value);
  7842. } else {
  7843. $round = pow(10,abs($decimals));
  7844. if ($value < 0) { $round = 0-$round; }
  7845. $value = self::MROUND($value,$round);
  7846. // The implementation of money_format used if the standard PHP function is not available can't handle decimal places of 0,
  7847. // so we display to 1 dp and chop off that character and the decimal separator using substr
  7848. return substr(money_format('%.1n',$value),0,-2);
  7849. }
  7850. } // function DOLLAR()
  7851. /**
  7852. * DOLLARDE
  7853. *
  7854. * Converts a dollar price expressed as an integer part and a fraction part into a dollar price expressed as a decimal number.
  7855. * Fractional dollar numbers are sometimes used for security prices.
  7856. *
  7857. * @param float $fractional_dollar Fractional Dollar
  7858. * @param int $fraction Fraction
  7859. * @return float
  7860. */
  7861. public static function DOLLARDE($fractional_dollar = Null, $fraction = 0) {
  7862. $fractional_dollar = self::flattenSingleValue($fractional_dollar);
  7863. $fraction = (int)self::flattenSingleValue($fraction);
  7864. // Validate parameters
  7865. if (is_null($fractional_dollar) || $fraction < 0) {
  7866. return self::$_errorCodes['num'];
  7867. }
  7868. if ($fraction == 0) {
  7869. return self::$_errorCodes['divisionbyzero'];
  7870. }
  7871. $dollars = floor($fractional_dollar);
  7872. $cents = fmod($fractional_dollar,1);
  7873. $cents /= $fraction;
  7874. $cents *= pow(10,ceil(log10($fraction)));
  7875. return $dollars + $cents;
  7876. } // function DOLLARDE()
  7877. /**
  7878. * DOLLARFR
  7879. *
  7880. * Converts a dollar price expressed as a decimal number into a dollar price expressed as a fraction.
  7881. * Fractional dollar numbers are sometimes used for security prices.
  7882. *
  7883. * @param float $decimal_dollar Decimal Dollar
  7884. * @param int $fraction Fraction
  7885. * @return float
  7886. */
  7887. public static function DOLLARFR($decimal_dollar = Null, $fraction = 0) {
  7888. $decimal_dollar = self::flattenSingleValue($decimal_dollar);
  7889. $fraction = (int)self::flattenSingleValue($fraction);
  7890. // Validate parameters
  7891. if (is_null($decimal_dollar) || $fraction < 0) {
  7892. return self::$_errorCodes['num'];
  7893. }
  7894. if ($fraction == 0) {
  7895. return self::$_errorCodes['divisionbyzero'];
  7896. }
  7897. $dollars = floor($decimal_dollar);
  7898. $cents = fmod($decimal_dollar,1);
  7899. $cents *= $fraction;
  7900. $cents *= pow(10,-ceil(log10($fraction)));
  7901. return $dollars + $cents;
  7902. } // function DOLLARFR()
  7903. /**
  7904. * EFFECT
  7905. *
  7906. * Returns the effective interest rate given the nominal rate and the number of compounding payments per year.
  7907. *
  7908. * @param float $nominal_rate Nominal interest rate
  7909. * @param int $npery Number of compounding payments per year
  7910. * @return float
  7911. */
  7912. public static function EFFECT($nominal_rate = 0, $npery = 0) {
  7913. $nominal_rate = self::flattenSingleValue($nominal_rate);
  7914. $npery = (int)self::flattenSingleValue($npery);
  7915. // Validate parameters
  7916. if ($nominal_rate <= 0 || $npery < 1) {
  7917. return self::$_errorCodes['num'];
  7918. }
  7919. return pow((1 + $nominal_rate / $npery), $npery) - 1;
  7920. } // function EFFECT()
  7921. /**
  7922. * NOMINAL
  7923. *
  7924. * Returns the nominal interest rate given the effective rate and the number of compounding payments per year.
  7925. *
  7926. * @param float $effect_rate Effective interest rate
  7927. * @param int $npery Number of compounding payments per year
  7928. * @return float
  7929. */
  7930. public static function NOMINAL($effect_rate = 0, $npery = 0) {
  7931. $effect_rate = self::flattenSingleValue($effect_rate);
  7932. $npery = (int)self::flattenSingleValue($npery);
  7933. // Validate parameters
  7934. if ($effect_rate <= 0 || $npery < 1) {
  7935. return self::$_errorCodes['num'];
  7936. }
  7937. // Calculate
  7938. return $npery * (pow($effect_rate + 1, 1 / $npery) - 1);
  7939. } // function NOMINAL()
  7940. /**
  7941. * PV
  7942. *
  7943. * Returns the Present Value of a cash flow with constant payments and interest rate (annuities).
  7944. *
  7945. * @param float $rate Interest rate per period
  7946. * @param int $nper Number of periods
  7947. * @param float $pmt Periodic payment (annuity)
  7948. * @param float $fv Future Value
  7949. * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
  7950. * @return float
  7951. */
  7952. public static function PV($rate = 0, $nper = 0, $pmt = 0, $fv = 0, $type = 0) {
  7953. $rate = self::flattenSingleValue($rate);
  7954. $nper = self::flattenSingleValue($nper);
  7955. $pmt = self::flattenSingleValue($pmt);
  7956. $fv = self::flattenSingleValue($fv);
  7957. $type = self::flattenSingleValue($type);
  7958. // Validate parameters
  7959. if ($type != 0 && $type != 1) {
  7960. return self::$_errorCodes['num'];
  7961. }
  7962. // Calculate
  7963. if (!is_null($rate) && $rate != 0) {
  7964. return (-$pmt * (1 + $rate * $type) * ((pow(1 + $rate, $nper) - 1) / $rate) - $fv) / pow(1 + $rate, $nper);
  7965. } else {
  7966. return -$fv - $pmt * $nper;
  7967. }
  7968. } // function PV()
  7969. /**
  7970. * FV
  7971. *
  7972. * Returns the Future Value of a cash flow with constant payments and interest rate (annuities).
  7973. *
  7974. * @param float $rate Interest rate per period
  7975. * @param int $nper Number of periods
  7976. * @param float $pmt Periodic payment (annuity)
  7977. * @param float $pv Present Value
  7978. * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
  7979. * @return float
  7980. */
  7981. public static function FV($rate = 0, $nper = 0, $pmt = 0, $pv = 0, $type = 0) {
  7982. $rate = self::flattenSingleValue($rate);
  7983. $nper = self::flattenSingleValue($nper);
  7984. $pmt = self::flattenSingleValue($pmt);
  7985. $pv = self::flattenSingleValue($pv);
  7986. $type = self::flattenSingleValue($type);
  7987. // Validate parameters
  7988. if ($type != 0 && $type != 1) {
  7989. return self::$_errorCodes['num'];
  7990. }
  7991. // Calculate
  7992. if (!is_null($rate) && $rate != 0) {
  7993. return -$pv * pow(1 + $rate, $nper) - $pmt * (1 + $rate * $type) * (pow(1 + $rate, $nper) - 1) / $rate;
  7994. } else {
  7995. return -$pv - $pmt * $nper;
  7996. }
  7997. } // function FV()
  7998. /**
  7999. * FVSCHEDULE
  8000. *
  8001. */
  8002. public static function FVSCHEDULE($principal, $schedule) {
  8003. $principal = self::flattenSingleValue($principal);
  8004. $schedule = self::flattenArray($schedule);
  8005. foreach($schedule as $n) {
  8006. $principal *= 1 + $n;
  8007. }
  8008. return $principal;
  8009. } // function FVSCHEDULE()
  8010. /**
  8011. * PMT
  8012. *
  8013. * Returns the constant payment (annuity) for a cash flow with a constant interest rate.
  8014. *
  8015. * @param float $rate Interest rate per period
  8016. * @param int $nper Number of periods
  8017. * @param float $pv Present Value
  8018. * @param float $fv Future Value
  8019. * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
  8020. * @return float
  8021. */
  8022. public static function PMT($rate = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0) {
  8023. $rate = self::flattenSingleValue($rate);
  8024. $nper = self::flattenSingleValue($nper);
  8025. $pv = self::flattenSingleValue($pv);
  8026. $fv = self::flattenSingleValue($fv);
  8027. $type = self::flattenSingleValue($type);
  8028. // Validate parameters
  8029. if ($type != 0 && $type != 1) {
  8030. return self::$_errorCodes['num'];
  8031. }
  8032. // Calculate
  8033. if (!is_null($rate) && $rate != 0) {
  8034. return (-$fv - $pv * pow(1 + $rate, $nper)) / (1 + $rate * $type) / ((pow(1 + $rate, $nper) - 1) / $rate);
  8035. } else {
  8036. return (-$pv - $fv) / $nper;
  8037. }
  8038. } // function PMT()
  8039. /**
  8040. * NPER
  8041. *
  8042. * Returns the number of periods for a cash flow with constant periodic payments (annuities), and interest rate.
  8043. *
  8044. * @param float $rate Interest rate per period
  8045. * @param int $pmt Periodic payment (annuity)
  8046. * @param float $pv Present Value
  8047. * @param float $fv Future Value
  8048. * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
  8049. * @return float
  8050. */
  8051. public static function NPER($rate = 0, $pmt = 0, $pv = 0, $fv = 0, $type = 0) {
  8052. $rate = self::flattenSingleValue($rate);
  8053. $pmt = self::flattenSingleValue($pmt);
  8054. $pv = self::flattenSingleValue($pv);
  8055. $fv = self::flattenSingleValue($fv);
  8056. $type = self::flattenSingleValue($type);
  8057. // Validate parameters
  8058. if ($type != 0 && $type != 1) {
  8059. return self::$_errorCodes['num'];
  8060. }
  8061. // Calculate
  8062. if (!is_null($rate) && $rate != 0) {
  8063. if ($pmt == 0 && $pv == 0) {
  8064. return self::$_errorCodes['num'];
  8065. }
  8066. return log(($pmt * (1 + $rate * $type) / $rate - $fv) / ($pv + $pmt * (1 + $rate * $type) / $rate)) / log(1 + $rate);
  8067. } else {
  8068. if ($pmt == 0) {
  8069. return self::$_errorCodes['num'];
  8070. }
  8071. return (-$pv -$fv) / $pmt;
  8072. }
  8073. } // function NPER()
  8074. private static function _interestAndPrincipal($rate=0, $per=0, $nper=0, $pv=0, $fv=0, $type=0) {
  8075. $pmt = self::PMT($rate, $nper, $pv, $fv, $type);
  8076. $capital = $pv;
  8077. for ($i = 1; $i<= $per; ++$i) {
  8078. $interest = ($type && $i == 1)? 0 : -$capital * $rate;
  8079. $principal = $pmt - $interest;
  8080. $capital += $principal;
  8081. }
  8082. return array($interest, $principal);
  8083. } // function _interestAndPrincipal()
  8084. /**
  8085. * IPMT
  8086. *
  8087. * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate.
  8088. *
  8089. * @param float $rate Interest rate per period
  8090. * @param int $per Period for which we want to find the interest
  8091. * @param int $nper Number of periods
  8092. * @param float $pv Present Value
  8093. * @param float $fv Future Value
  8094. * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
  8095. * @return float
  8096. */
  8097. public static function IPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) {
  8098. $rate = self::flattenSingleValue($rate);
  8099. $per = (int) self::flattenSingleValue($per);
  8100. $nper = (int) self::flattenSingleValue($nper);
  8101. $pv = self::flattenSingleValue($pv);
  8102. $fv = self::flattenSingleValue($fv);
  8103. $type = (int) self::flattenSingleValue($type);
  8104. // Validate parameters
  8105. if ($type != 0 && $type != 1) {
  8106. return self::$_errorCodes['num'];
  8107. }
  8108. if ($per <= 0 || $per > $nper) {
  8109. return self::$_errorCodes['value'];
  8110. }
  8111. // Calculate
  8112. $interestAndPrincipal = self::_interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type);
  8113. return $interestAndPrincipal[0];
  8114. } // function IPMT()
  8115. /**
  8116. * CUMIPMT
  8117. *
  8118. * Returns the cumulative interest paid on a loan between start_period and end_period.
  8119. *
  8120. * @param float $rate Interest rate per period
  8121. * @param int $nper Number of periods
  8122. * @param float $pv Present Value
  8123. * @param int start The first period in the calculation.
  8124. * Payment periods are numbered beginning with 1.
  8125. * @param int end The last period in the calculation.
  8126. * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
  8127. * @return float
  8128. */
  8129. public static function CUMIPMT($rate, $nper, $pv, $start, $end, $type = 0) {
  8130. $rate = self::flattenSingleValue($rate);
  8131. $nper = (int) self::flattenSingleValue($nper);
  8132. $pv = self::flattenSingleValue($pv);
  8133. $start = (int) self::flattenSingleValue($start);
  8134. $end = (int) self::flattenSingleValue($end);
  8135. $type = (int) self::flattenSingleValue($type);
  8136. // Validate parameters
  8137. if ($type != 0 && $type != 1) {
  8138. return self::$_errorCodes['num'];
  8139. }
  8140. if ($start < 1 || $start > $end) {
  8141. return self::$_errorCodes['value'];
  8142. }
  8143. // Calculate
  8144. $interest = 0;
  8145. for ($per = $start; $per <= $end; ++$per) {
  8146. $interest += self::IPMT($rate, $per, $nper, $pv, 0, $type);
  8147. }
  8148. return $interest;
  8149. } // function CUMIPMT()
  8150. /**
  8151. * PPMT
  8152. *
  8153. * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate.
  8154. *
  8155. * @param float $rate Interest rate per period
  8156. * @param int $per Period for which we want to find the interest
  8157. * @param int $nper Number of periods
  8158. * @param float $pv Present Value
  8159. * @param float $fv Future Value
  8160. * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
  8161. * @return float
  8162. */
  8163. public static function PPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) {
  8164. $rate = self::flattenSingleValue($rate);
  8165. $per = (int) self::flattenSingleValue($per);
  8166. $nper = (int) self::flattenSingleValue($nper);
  8167. $pv = self::flattenSingleValue($pv);
  8168. $fv = self::flattenSingleValue($fv);
  8169. $type = (int) self::flattenSingleValue($type);
  8170. // Validate parameters
  8171. if ($type != 0 && $type != 1) {
  8172. return self::$_errorCodes['num'];
  8173. }
  8174. if ($per <= 0 || $per > $nper) {
  8175. return self::$_errorCodes['value'];
  8176. }
  8177. // Calculate
  8178. $interestAndPrincipal = self::_interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type);
  8179. return $interestAndPrincipal[1];
  8180. } // function PPMT()
  8181. /**
  8182. * CUMPRINC
  8183. *
  8184. * Returns the cumulative principal paid on a loan between start_period and end_period.
  8185. *
  8186. * @param float $rate Interest rate per period
  8187. * @param int $nper Number of periods
  8188. * @param float $pv Present Value
  8189. * @param int start The first period in the calculation.
  8190. * Payment periods are numbered beginning with 1.
  8191. * @param int end The last period in the calculation.
  8192. * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
  8193. * @return float
  8194. */
  8195. public static function CUMPRINC($rate, $nper, $pv, $start, $end, $type = 0) {
  8196. $rate = self::flattenSingleValue($rate);
  8197. $nper = (int) self::flattenSingleValue($nper);
  8198. $pv = self::flattenSingleValue($pv);
  8199. $start = (int) self::flattenSingleValue($start);
  8200. $end = (int) self::flattenSingleValue($end);
  8201. $type = (int) self::flattenSingleValue($type);
  8202. // Validate parameters
  8203. if ($type != 0 && $type != 1) {
  8204. return self::$_errorCodes['num'];
  8205. }
  8206. if ($start < 1 || $start > $end) {
  8207. return self::$_errorCodes['value'];
  8208. }
  8209. // Calculate
  8210. $principal = 0;
  8211. for ($per = $start; $per <= $end; ++$per) {
  8212. $principal += self::PPMT($rate, $per, $nper, $pv, 0, $type);
  8213. }
  8214. return $principal;
  8215. } // function CUMPRINC()
  8216. /**
  8217. * ISPMT
  8218. *
  8219. * Returns the interest payment for an investment based on an interest rate and a constant payment schedule.
  8220. *
  8221. * Excel Function:
  8222. * =ISPMT(interest_rate, period, number_payments, PV)
  8223. *
  8224. * interest_rate is the interest rate for the investment
  8225. *
  8226. * period is the period to calculate the interest rate. It must be betweeen 1 and number_payments.
  8227. *
  8228. * number_payments is the number of payments for the annuity
  8229. *
  8230. * PV is the loan amount or present value of the payments
  8231. */
  8232. public static function ISPMT() {
  8233. // Return value
  8234. $returnValue = 0;
  8235. // Get the parameters
  8236. $aArgs = self::flattenArray(func_get_args());
  8237. $interestRate = array_shift($aArgs);
  8238. $period = array_shift($aArgs);
  8239. $numberPeriods = array_shift($aArgs);
  8240. $principleRemaining = array_shift($aArgs);
  8241. // Calculate
  8242. $principlePayment = ($principleRemaining * 1.0) / ($numberPeriods * 1.0);
  8243. for($i=0; $i <= $period; ++$i) {
  8244. $returnValue = $interestRate * $principleRemaining * -1;
  8245. $principleRemaining -= $principlePayment;
  8246. // principle needs to be 0 after the last payment, don't let floating point screw it up
  8247. if($i == $numberPeriods) {
  8248. $returnValue = 0;
  8249. }
  8250. }
  8251. return($returnValue);
  8252. } // function ISPMT()
  8253. /**
  8254. * NPV
  8255. *
  8256. * Returns the Net Present Value of a cash flow series given a discount rate.
  8257. *
  8258. * @param float Discount interest rate
  8259. * @param array Cash flow series
  8260. * @return float
  8261. */
  8262. public static function NPV() {
  8263. // Return value
  8264. $returnValue = 0;
  8265. // Loop through arguments
  8266. $aArgs = self::flattenArray(func_get_args());
  8267. // Calculate
  8268. $rate = array_shift($aArgs);
  8269. for ($i = 1; $i <= count($aArgs); ++$i) {
  8270. // Is it a numeric value?
  8271. if (is_numeric($aArgs[$i - 1])) {
  8272. $returnValue += $aArgs[$i - 1] / pow(1 + $rate, $i);
  8273. }
  8274. }
  8275. // Return
  8276. return $returnValue;
  8277. } // function NPV()
  8278. /**
  8279. * XNPV
  8280. *
  8281. * Returns the net present value for a schedule of cash flows that is not necessarily periodic.
  8282. * To calculate the net present value for a series of cash flows that is periodic, use the NPV function.
  8283. *
  8284. * @param float Discount interest rate
  8285. * @param array Cash flow series
  8286. * @return float
  8287. */
  8288. public static function XNPV($rate, $values, $dates) {
  8289. if ((!is_array($values)) || (!is_array($dates))) return self::$_errorCodes['value'];
  8290. $values = self::flattenArray($values);
  8291. $dates = self::flattenArray($dates);
  8292. $valCount = count($values);
  8293. if ($valCount != count($dates)) return self::$_errorCodes['num'];
  8294. $xnpv = 0.0;
  8295. for ($i = 0; $i < $valCount; ++$i) {
  8296. $xnpv += $values[$i] / pow(1 + $rate, self::DATEDIF($dates[0],$dates[$i],'d') / 365);
  8297. }
  8298. return (is_finite($xnpv) ? $xnpv : self::$_errorCodes['value']);
  8299. } // function XNPV()
  8300. public static function IRR($values, $guess = 0.1) {
  8301. if (!is_array($values)) return self::$_errorCodes['value'];
  8302. $values = self::flattenArray($values);
  8303. $guess = self::flattenSingleValue($guess);
  8304. // create an initial range, with a root somewhere between 0 and guess
  8305. $x1 = 0.0;
  8306. $x2 = $guess;
  8307. $f1 = self::NPV($x1, $values);
  8308. $f2 = self::NPV($x2, $values);
  8309. for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
  8310. if (($f1 * $f2) < 0.0) break;
  8311. if (abs($f1) < abs($f2)) {
  8312. $f1 = self::NPV($x1 += 1.6 * ($x1 - $x2), $values);
  8313. } else {
  8314. $f2 = self::NPV($x2 += 1.6 * ($x2 - $x1), $values);
  8315. }
  8316. }
  8317. if (($f1 * $f2) > 0.0) return self::$_errorCodes['value'];
  8318. $f = self::NPV($x1, $values);
  8319. if ($f < 0.0) {
  8320. $rtb = $x1;
  8321. $dx = $x2 - $x1;
  8322. } else {
  8323. $rtb = $x2;
  8324. $dx = $x1 - $x2;
  8325. }
  8326. for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
  8327. $dx *= 0.5;
  8328. $x_mid = $rtb + $dx;
  8329. $f_mid = self::NPV($x_mid, $values);
  8330. if ($f_mid <= 0.0) $rtb = $x_mid;
  8331. if ((abs($f_mid) < FINANCIAL_PRECISION) || (abs($dx) < FINANCIAL_PRECISION)) return $x_mid;
  8332. }
  8333. return self::$_errorCodes['value'];
  8334. } // function IRR()
  8335. public static function MIRR($values, $finance_rate, $reinvestment_rate) {
  8336. if (!is_array($values)) return self::$_errorCodes['value'];
  8337. $values = self::flattenArray($values);
  8338. $finance_rate = self::flattenSingleValue($finance_rate);
  8339. $reinvestment_rate = self::flattenSingleValue($reinvestment_rate);
  8340. $n = count($values);
  8341. $rr = 1.0 + $reinvestment_rate;
  8342. $fr = 1.0 + $finance_rate;
  8343. $npv_pos = $npv_neg = 0.0;
  8344. foreach($values as $i => $v) {
  8345. if ($v >= 0) {
  8346. $npv_pos += $v / pow($rr, $i);
  8347. } else {
  8348. $npv_neg += $v / pow($fr, $i);
  8349. }
  8350. }
  8351. if (($npv_neg == 0) || ($npv_pos == 0) || ($reinvestment_rate <= -1)) {
  8352. return self::$_errorCodes['value'];
  8353. }
  8354. $mirr = pow((-$npv_pos * pow($rr, $n))
  8355. / ($npv_neg * ($rr)), (1.0 / ($n - 1))) - 1.0;
  8356. return (is_finite($mirr) ? $mirr : self::$_errorCodes['value']);
  8357. } // function MIRR()
  8358. public static function XIRR($values, $dates, $guess = 0.1) {
  8359. if ((!is_array($values)) && (!is_array($dates))) return self::$_errorCodes['value'];
  8360. $values = self::flattenArray($values);
  8361. $dates = self::flattenArray($dates);
  8362. $guess = self::flattenSingleValue($guess);
  8363. if (count($values) != count($dates)) return self::$_errorCodes['num'];
  8364. // create an initial range, with a root somewhere between 0 and guess
  8365. $x1 = 0.0;
  8366. $x2 = $guess;
  8367. $f1 = self::XNPV($x1, $values, $dates);
  8368. $f2 = self::XNPV($x2, $values, $dates);
  8369. for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
  8370. if (($f1 * $f2) < 0.0) break;
  8371. if (abs($f1) < abs($f2)) {
  8372. $f1 = self::XNPV($x1 += 1.6 * ($x1 - $x2), $values, $dates);
  8373. } else {
  8374. $f2 = self::XNPV($x2 += 1.6 * ($x2 - $x1), $values, $dates);
  8375. }
  8376. }
  8377. if (($f1 * $f2) > 0.0) return self::$_errorCodes['value'];
  8378. $f = self::XNPV($x1, $values, $dates);
  8379. if ($f < 0.0) {
  8380. $rtb = $x1;
  8381. $dx = $x2 - $x1;
  8382. } else {
  8383. $rtb = $x2;
  8384. $dx = $x1 - $x2;
  8385. }
  8386. for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
  8387. $dx *= 0.5;
  8388. $x_mid = $rtb + $dx;
  8389. $f_mid = self::XNPV($x_mid, $values, $dates);
  8390. if ($f_mid <= 0.0) $rtb = $x_mid;
  8391. if ((abs($f_mid) < FINANCIAL_PRECISION) || (abs($dx) < FINANCIAL_PRECISION)) return $x_mid;
  8392. }
  8393. return self::$_errorCodes['value'];
  8394. }
  8395. /**
  8396. * RATE
  8397. *
  8398. **/
  8399. public static function RATE($nper, $pmt, $pv, $fv = 0.0, $type = 0, $guess = 0.1) {
  8400. $nper = (int) self::flattenSingleValue($nper);
  8401. $pmt = self::flattenSingleValue($pmt);
  8402. $pv = self::flattenSingleValue($pv);
  8403. $fv = (is_null($fv)) ? 0.0 : self::flattenSingleValue($fv);
  8404. $type = (is_null($type)) ? 0 : (int) self::flattenSingleValue($type);
  8405. $guess = (is_null($guess)) ? 0.1 : self::flattenSingleValue($guess);
  8406. $rate = $guess;
  8407. if (abs($rate) < FINANCIAL_PRECISION) {
  8408. $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv;
  8409. } else {
  8410. $f = exp($nper * log(1 + $rate));
  8411. $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
  8412. }
  8413. $y0 = $pv + $pmt * $nper + $fv;
  8414. $y1 = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
  8415. // find root by secant method
  8416. $i = $x0 = 0.0;
  8417. $x1 = $rate;
  8418. while ((abs($y0 - $y1) > FINANCIAL_PRECISION) && ($i < FINANCIAL_MAX_ITERATIONS)) {
  8419. $rate = ($y1 * $x0 - $y0 * $x1) / ($y1 - $y0);
  8420. $x0 = $x1;
  8421. $x1 = $rate;
  8422. if (abs($rate) < FINANCIAL_PRECISION) {
  8423. $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv;
  8424. } else {
  8425. $f = exp($nper * log(1 + $rate));
  8426. $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
  8427. }
  8428. $y0 = $y1;
  8429. $y1 = $y;
  8430. ++$i;
  8431. }
  8432. return $rate;
  8433. } // function RATE()
  8434. /**
  8435. * DB
  8436. *
  8437. * Returns the depreciation of an asset for a specified period using the fixed-declining balance method.
  8438. * This form of depreciation is used if you want to get a higher depreciation value at the beginning of the depreciation
  8439. * (as opposed to linear depreciation). The depreciation value is reduced with every depreciation period by the
  8440. * depreciation already deducted from the initial cost.
  8441. *
  8442. * @param float cost Initial cost of the asset.
  8443. * @param float salvage Value at the end of the depreciation. (Sometimes called the salvage value of the asset)
  8444. * @param int life Number of periods over which the asset is depreciated. (Sometimes called the useful life of the asset)
  8445. * @param int period The period for which you want to calculate the depreciation. Period must use the same units as life.
  8446. * @param float month Number of months in the first year. If month is omitted, it defaults to 12.
  8447. * @return float
  8448. */
  8449. public static function DB($cost, $salvage, $life, $period, $month=12) {
  8450. $cost = (float) self::flattenSingleValue($cost);
  8451. $salvage = (float) self::flattenSingleValue($salvage);
  8452. $life = (int) self::flattenSingleValue($life);
  8453. $period = (int) self::flattenSingleValue($period);
  8454. $month = (int) self::flattenSingleValue($month);
  8455. // Validate
  8456. if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($month))) {
  8457. if ($cost == 0) {
  8458. return 0.0;
  8459. } elseif (($cost < 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($month < 1)) {
  8460. return self::$_errorCodes['num'];
  8461. }
  8462. // Set Fixed Depreciation Rate
  8463. $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life));
  8464. $fixedDepreciationRate = round($fixedDepreciationRate, 3);
  8465. // Loop through each period calculating the depreciation
  8466. $previousDepreciation = 0;
  8467. for ($per = 1; $per <= $period; ++$per) {
  8468. if ($per == 1) {
  8469. $depreciation = $cost * $fixedDepreciationRate * $month / 12;
  8470. } elseif ($per == ($life + 1)) {
  8471. $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate * (12 - $month) / 12;
  8472. } else {
  8473. $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate;
  8474. }
  8475. $previousDepreciation += $depreciation;
  8476. }
  8477. if (self::$compatibilityMode == self::COMPATIBILITY_GNUMERIC) {
  8478. $depreciation = round($depreciation,2);
  8479. }
  8480. return $depreciation;
  8481. }
  8482. return self::$_errorCodes['value'];
  8483. } // function DB()
  8484. /**
  8485. * DDB
  8486. *
  8487. * Returns the depreciation of an asset for a specified period using the double-declining balance method or some other method you specify.
  8488. *
  8489. * @param float cost Initial cost of the asset.
  8490. * @param float salvage Value at the end of the depreciation. (Sometimes called the salvage value of the asset)
  8491. * @param int life Number of periods over which the asset is depreciated. (Sometimes called the useful life of the asset)
  8492. * @param int period The period for which you want to calculate the depreciation. Period must use the same units as life.
  8493. * @param float factor The rate at which the balance declines.
  8494. * If factor is omitted, it is assumed to be 2 (the double-declining balance method).
  8495. * @return float
  8496. */
  8497. public static function DDB($cost, $salvage, $life, $period, $factor=2.0) {
  8498. $cost = (float) self::flattenSingleValue($cost);
  8499. $salvage = (float) self::flattenSingleValue($salvage);
  8500. $life = (int) self::flattenSingleValue($life);
  8501. $period = (int) self::flattenSingleValue($period);
  8502. $factor = (float) self::flattenSingleValue($factor);
  8503. // Validate
  8504. if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($factor))) {
  8505. if (($cost <= 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($factor <= 0.0) || ($period > $life)) {
  8506. return self::$_errorCodes['num'];
  8507. }
  8508. // Set Fixed Depreciation Rate
  8509. $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life));
  8510. $fixedDepreciationRate = round($fixedDepreciationRate, 3);
  8511. // Loop through each period calculating the depreciation
  8512. $previousDepreciation = 0;
  8513. for ($per = 1; $per <= $period; ++$per) {
  8514. $depreciation = min( ($cost - $previousDepreciation) * ($factor / $life), ($cost - $salvage - $previousDepreciation) );
  8515. $previousDepreciation += $depreciation;
  8516. }
  8517. if (self::$compatibilityMode == self::COMPATIBILITY_GNUMERIC) {
  8518. $depreciation = round($depreciation,2);
  8519. }
  8520. return $depreciation;
  8521. }
  8522. return self::$_errorCodes['value'];
  8523. } // function DDB()
  8524. private static function _daysPerYear($year,$basis) {
  8525. switch ($basis) {
  8526. case 0 :
  8527. case 2 :
  8528. case 4 :
  8529. $daysPerYear = 360;
  8530. break;
  8531. case 3 :
  8532. $daysPerYear = 365;
  8533. break;
  8534. case 1 :
  8535. if (self::_isLeapYear(self::YEAR($year))) {
  8536. $daysPerYear = 366;
  8537. } else {
  8538. $daysPerYear = 365;
  8539. }
  8540. break;
  8541. default :
  8542. return self::$_errorCodes['num'];
  8543. }
  8544. return $daysPerYear;
  8545. } // function _daysPerYear()
  8546. /**
  8547. * ACCRINT
  8548. *
  8549. * Returns the discount rate for a security.
  8550. *
  8551. * @param mixed issue The security's issue date.
  8552. * @param mixed firstinter The security's first interest date.
  8553. * @param mixed settlement The security's settlement date.
  8554. * @param float rate The security's annual coupon rate.
  8555. * @param float par The security's par value.
  8556. * @param int basis The type of day count to use.
  8557. * 0 or omitted US (NASD) 30/360
  8558. * 1 Actual/actual
  8559. * 2 Actual/360
  8560. * 3 Actual/365
  8561. * 4 European 30/360
  8562. * @return float
  8563. */
  8564. public static function ACCRINT($issue, $firstinter, $settlement, $rate, $par=1000, $frequency=1, $basis=0) {
  8565. $issue = self::flattenSingleValue($issue);
  8566. $firstinter = self::flattenSingleValue($firstinter);
  8567. $settlement = self::flattenSingleValue($settlement);
  8568. $rate = (float) self::flattenSingleValue($rate);
  8569. $par = (is_null($par)) ? 1000 : (float) self::flattenSingleValue($par);
  8570. $frequency = (is_null($frequency)) ? 1 : (int) self::flattenSingleValue($frequency);
  8571. $basis = (is_null($basis)) ? 0 : (int) self::flattenSingleValue($basis);
  8572. // Validate
  8573. if ((is_numeric($rate)) && (is_numeric($par))) {
  8574. if (($rate <= 0) || ($par <= 0)) {
  8575. return self::$_errorCodes['num'];
  8576. }
  8577. $daysBetweenIssueAndSettlement = self::YEARFRAC($issue, $settlement, $basis);
  8578. if (!is_numeric($daysBetweenIssueAndSettlement)) {
  8579. return $daysBetweenIssueAndSettlement;
  8580. }
  8581. $daysPerYear = self::_daysPerYear(self::YEAR($issue),$basis);
  8582. if (!is_numeric($daysPerYear)) {
  8583. return $daysPerYear;
  8584. }
  8585. $daysBetweenIssueAndSettlement *= $daysPerYear;
  8586. return $par * $rate * ($daysBetweenIssueAndSettlement / $daysPerYear);
  8587. }
  8588. return self::$_errorCodes['value'];
  8589. } // function ACCRINT()
  8590. /**
  8591. * ACCRINTM
  8592. *
  8593. * Returns the discount rate for a security.
  8594. *
  8595. * @param mixed issue The security's issue date.
  8596. * @param mixed settlement The security's settlement date.
  8597. * @param float rate The security's annual coupon rate.
  8598. * @param float par The security's par value.
  8599. * @param int basis The type of day count to use.
  8600. * 0 or omitted US (NASD) 30/360
  8601. * 1 Actual/actual
  8602. * 2 Actual/360
  8603. * 3 Actual/365
  8604. * 4 European 30/360
  8605. * @return float
  8606. */
  8607. public static function ACCRINTM($issue, $settlement, $rate, $par=1000, $basis=0) {
  8608. $issue = self::flattenSingleValue($issue);
  8609. $settlement = self::flattenSingleValue($settlement);
  8610. $rate = (float) self::flattenSingleValue($rate);
  8611. $par = (is_null($par)) ? 1000 : (float) self::flattenSingleValue($par);
  8612. $basis = (is_null($basis)) ? 0 : (int) self::flattenSingleValue($basis);
  8613. // Validate
  8614. if ((is_numeric($rate)) && (is_numeric($par))) {
  8615. if (($rate <= 0) || ($par <= 0)) {
  8616. return self::$_errorCodes['num'];
  8617. }
  8618. $daysBetweenIssueAndSettlement = self::YEARFRAC($issue, $settlement, $basis);
  8619. if (!is_numeric($daysBetweenIssueAndSettlement)) {
  8620. return $daysBetweenIssueAndSettlement;
  8621. }
  8622. $daysPerYear = self::_daysPerYear(self::YEAR($issue),$basis);
  8623. if (!is_numeric($daysPerYear)) {
  8624. return $daysPerYear;
  8625. }
  8626. $daysBetweenIssueAndSettlement *= $daysPerYear;
  8627. return $par * $rate * ($daysBetweenIssueAndSettlement / $daysPerYear);
  8628. }
  8629. return self::$_errorCodes['value'];
  8630. } // function ACCRINTM()
  8631. public static function AMORDEGRC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis=0) {
  8632. $cost = self::flattenSingleValue($cost);
  8633. $purchased = self::flattenSingleValue($purchased);
  8634. $firstPeriod = self::flattenSingleValue($firstPeriod);
  8635. $salvage = self::flattenSingleValue($salvage);
  8636. $period = floor(self::flattenSingleValue($period));
  8637. $rate = self::flattenSingleValue($rate);
  8638. $basis = floor(self::flattenSingleValue($basis));
  8639. $fUsePer = 1.0 / $rate;
  8640. if ($fUsePer < 3.0) {
  8641. $amortiseCoeff = 1.0;
  8642. } elseif ($fUsePer < 5.0) {
  8643. $amortiseCoeff = 1.5;
  8644. } elseif ($fUsePer <= 6.0) {
  8645. $amortiseCoeff = 2.0;
  8646. } else {
  8647. $amortiseCoeff = 2.5;
  8648. }
  8649. $rate *= $amortiseCoeff;
  8650. $fNRate = floor((self::YEARFRAC($purchased, $firstPeriod, $basis) * $rate * $cost) + 0.5);
  8651. $cost -= $fNRate;
  8652. $fRest = $cost - $salvage;
  8653. for ($n = 0; $n < $period; ++$n) {
  8654. $fNRate = floor(($rate * $cost) + 0.5);
  8655. $fRest -= $fNRate;
  8656. if ($fRest < 0.0) {
  8657. switch ($period - $n) {
  8658. case 0 :
  8659. case 1 : return floor(($cost * 0.5) + 0.5);
  8660. break;
  8661. default : return 0.0;
  8662. break;
  8663. }
  8664. }
  8665. $cost -= $fNRate;
  8666. }
  8667. return $fNRate;
  8668. } // function AMORDEGRC()
  8669. public static function AMORLINC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis=0) {
  8670. $cost = self::flattenSingleValue($cost);
  8671. $purchased = self::flattenSingleValue($purchased);
  8672. $firstPeriod = self::flattenSingleValue($firstPeriod);
  8673. $salvage = self::flattenSingleValue($salvage);
  8674. $period = self::flattenSingleValue($period);
  8675. $rate = self::flattenSingleValue($rate);
  8676. $basis = self::flattenSingleValue($basis);
  8677. $fOneRate = $cost * $rate;
  8678. $fCostDelta = $cost - $salvage;
  8679. $f0Rate = self::YEARFRAC($purchased, $firstPeriod, $basis) * $rate * $cost;
  8680. $nNumOfFullPeriods = intval(($cost - $salvage - $f0Rate) / $fOneRate);
  8681. if ($period == 0) {
  8682. return $f0Rate;
  8683. } elseif ($period <= $nNumOfFullPeriods) {
  8684. return $fOneRate;
  8685. } elseif ($period == ($nNumOfFullPeriods + 1)) {
  8686. return ($fCostDelta - $fOneRate * $nNumOfFullPeriods - $f0Rate);
  8687. } else {
  8688. return 0.0;
  8689. }
  8690. } // function AMORLINC()
  8691. public static function COUPNUM($settlement, $maturity, $frequency, $basis=0) {
  8692. $settlement = self::flattenSingleValue($settlement);
  8693. $maturity = self::flattenSingleValue($maturity);
  8694. $frequency = self::flattenSingleValue($frequency);
  8695. $basis = self::flattenSingleValue($basis);
  8696. $daysBetweenSettlementAndMaturity = self::YEARFRAC($settlement, $maturity, $basis) * 365;
  8697. switch ($frequency) {
  8698. case 1: // annual payments
  8699. return ceil($daysBetweenSettlementAndMaturity / 360);
  8700. case 2: // half-yearly
  8701. return ceil($daysBetweenSettlementAndMaturity / 180);
  8702. case 4: // quarterly
  8703. return ceil($daysBetweenSettlementAndMaturity / 90);
  8704. }
  8705. return self::$_errorCodes['value'];
  8706. } // function COUPNUM()
  8707. public static function COUPDAYBS($settlement, $maturity, $frequency, $basis=0) {
  8708. $settlement = self::flattenSingleValue($settlement);
  8709. $maturity = self::flattenSingleValue($maturity);
  8710. $frequency = self::flattenSingleValue($frequency);
  8711. $basis = self::flattenSingleValue($basis);
  8712. $daysBetweenSettlementAndMaturity = self::YEARFRAC($settlement, $maturity, $basis) * 365;
  8713. switch ($frequency) {
  8714. case 1: // annual payments
  8715. return 365 - ($daysBetweenSettlementAndMaturity % 360);
  8716. case 2: // half-yearly
  8717. return 365 - ($daysBetweenSettlementAndMaturity % 360);
  8718. case 4: // quarterly
  8719. return self::DATEDIF($maturity, $settlement);
  8720. }
  8721. return self::$_errorCodes['value'];
  8722. } // function COUPDAYBS()
  8723. /**
  8724. * DISC
  8725. *
  8726. * Returns the discount rate for a security.
  8727. *
  8728. * @param mixed settlement The security's settlement date.
  8729. * The security settlement date is the date after the issue date when the security is traded to the buyer.
  8730. * @param mixed maturity The security's maturity date.
  8731. * The maturity date is the date when the security expires.
  8732. * @param int price The security's price per $100 face value.
  8733. * @param int redemption the security's redemption value per $100 face value.
  8734. * @param int basis The type of day count to use.
  8735. * 0 or omitted US (NASD) 30/360
  8736. * 1 Actual/actual
  8737. * 2 Actual/360
  8738. * 3 Actual/365
  8739. * 4 European 30/360
  8740. * @return float
  8741. */
  8742. public static function DISC($settlement, $maturity, $price, $redemption, $basis=0) {
  8743. $settlement = self::flattenSingleValue($settlement);
  8744. $maturity = self::flattenSingleValue($maturity);
  8745. $price = (float) self::flattenSingleValue($price);
  8746. $redemption = (float) self::flattenSingleValue($redemption);
  8747. $basis = (int) self::flattenSingleValue($basis);
  8748. // Validate
  8749. if ((is_numeric($price)) && (is_numeric($redemption)) && (is_numeric($basis))) {
  8750. if (($price <= 0) || ($redemption <= 0)) {
  8751. return self::$_errorCodes['num'];
  8752. }
  8753. $daysBetweenSettlementAndMaturity = self::YEARFRAC($settlement, $maturity, $basis);
  8754. if (!is_numeric($daysBetweenSettlementAndMaturity)) {
  8755. return $daysBetweenSettlementAndMaturity;
  8756. }
  8757. return ((1 - $price / $redemption) / $daysBetweenSettlementAndMaturity);
  8758. }
  8759. return self::$_errorCodes['value'];
  8760. } // function DISC()
  8761. /**
  8762. * PRICEDISC
  8763. *
  8764. * Returns the price per $100 face value of a discounted security.
  8765. *
  8766. * @param mixed settlement The security's settlement date.
  8767. * The security settlement date is the date after the issue date when the security is traded to the buyer.
  8768. * @param mixed maturity The security's maturity date.
  8769. * The maturity date is the date when the security expires.
  8770. * @param int discount The security's discount rate.
  8771. * @param int redemption The security's redemption value per $100 face value.
  8772. * @param int basis The type of day count to use.
  8773. * 0 or omitted US (NASD) 30/360
  8774. * 1 Actual/actual
  8775. * 2 Actual/360
  8776. * 3 Actual/365
  8777. * 4 European 30/360
  8778. * @return float
  8779. */
  8780. public static function PRICEDISC($settlement, $maturity, $discount, $redemption, $basis=0) {
  8781. $settlement = self::flattenSingleValue($settlement);
  8782. $maturity = self::flattenSingleValue($maturity);
  8783. $discount = (float) self::flattenSingleValue($discount);
  8784. $redemption = (float) self::flattenSingleValue($redemption);
  8785. $basis = (int) self::flattenSingleValue($basis);
  8786. // Validate
  8787. if ((is_numeric($discount)) && (is_numeric($redemption)) && (is_numeric($basis))) {
  8788. if (($discount <= 0) || ($redemption <= 0)) {
  8789. return self::$_errorCodes['num'];
  8790. }
  8791. $daysBetweenSettlementAndMaturity = self::YEARFRAC($settlement, $maturity, $basis);
  8792. if (!is_numeric($daysBetweenSettlementAndMaturity)) {
  8793. return $daysBetweenSettlementAndMaturity;
  8794. }
  8795. return $redemption * (1 - $discount * $daysBetweenSettlementAndMaturity);
  8796. }
  8797. return self::$_errorCodes['value'];
  8798. } // function PRICEDISC()
  8799. /**
  8800. * PRICEMAT
  8801. *
  8802. * Returns the price per $100 face value of a security that pays interest at maturity.
  8803. *
  8804. * @param mixed settlement The security's settlement date.
  8805. * The security's settlement date is the date after the issue date when the security is traded to the buyer.
  8806. * @param mixed maturity The security's maturity date.
  8807. * The maturity date is the date when the security expires.
  8808. * @param mixed issue The security's issue date.
  8809. * @param int rate The security's interest rate at date of issue.
  8810. * @param int yield The security's annual yield.
  8811. * @param int basis The type of day count to use.
  8812. * 0 or omitted US (NASD) 30/360
  8813. * 1 Actual/actual
  8814. * 2 Actual/360
  8815. * 3 Actual/365
  8816. * 4 European 30/360
  8817. * @return float
  8818. */
  8819. public static function PRICEMAT($settlement, $maturity, $issue, $rate, $yield, $basis=0) {
  8820. $settlement = self::flattenSingleValue($settlement);
  8821. $maturity = self::flattenSingleValue($maturity);
  8822. $issue = self::flattenSingleValue($issue);
  8823. $rate = self::flattenSingleValue($rate);
  8824. $yield = self::flattenSingleValue($yield);
  8825. $basis = (int) self::flattenSingleValue($basis);
  8826. // Validate
  8827. if (is_numeric($rate) && is_numeric($yield)) {
  8828. if (($rate <= 0) || ($yield <= 0)) {
  8829. return self::$_errorCodes['num'];
  8830. }
  8831. $daysPerYear = self::_daysPerYear(self::YEAR($settlement),$basis);
  8832. if (!is_numeric($daysPerYear)) {
  8833. return $daysPerYear;
  8834. }
  8835. $daysBetweenIssueAndSettlement = self::YEARFRAC($issue, $settlement, $basis);
  8836. if (!is_numeric($daysBetweenIssueAndSettlement)) {
  8837. return $daysBetweenIssueAndSettlement;
  8838. }
  8839. $daysBetweenIssueAndSettlement *= $daysPerYear;
  8840. $daysBetweenIssueAndMaturity = self::YEARFRAC($issue, $maturity, $basis);
  8841. if (!is_numeric($daysBetweenIssueAndMaturity)) {
  8842. return $daysBetweenIssueAndMaturity;
  8843. }
  8844. $daysBetweenIssueAndMaturity *= $daysPerYear;
  8845. $daysBetweenSettlementAndMaturity = self::YEARFRAC($settlement, $maturity, $basis);
  8846. if (!is_numeric($daysBetweenSettlementAndMaturity)) {
  8847. return $daysBetweenSettlementAndMaturity;
  8848. }
  8849. $daysBetweenSettlementAndMaturity *= $daysPerYear;
  8850. return ((100 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate * 100)) /
  8851. (1 + (($daysBetweenSettlementAndMaturity / $daysPerYear) * $yield)) -
  8852. (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate * 100));
  8853. }
  8854. return self::$_errorCodes['value'];
  8855. } // function PRICEMAT()
  8856. /**
  8857. * RECEIVED
  8858. *
  8859. * Returns the price per $100 face value of a discounted security.
  8860. *
  8861. * @param mixed settlement The security's settlement date.
  8862. * The security settlement date is the date after the issue date when the security is traded to the buyer.
  8863. * @param mixed maturity The security's maturity date.
  8864. * The maturity date is the date when the security expires.
  8865. * @param int investment The amount invested in the security.
  8866. * @param int discount The security's discount rate.
  8867. * @param int basis The type of day count to use.
  8868. * 0 or omitted US (NASD) 30/360
  8869. * 1 Actual/actual
  8870. * 2 Actual/360
  8871. * 3 Actual/365
  8872. * 4 European 30/360
  8873. * @return float
  8874. */
  8875. public static function RECEIVED($settlement, $maturity, $investment, $discount, $basis=0) {
  8876. $settlement = self::flattenSingleValue($settlement);
  8877. $maturity = self::flattenSingleValue($maturity);
  8878. $investment = (float) self::flattenSingleValue($investment);
  8879. $discount = (float) self::flattenSingleValue($discount);
  8880. $basis = (int) self::flattenSingleValue($basis);
  8881. // Validate
  8882. if ((is_numeric($investment)) && (is_numeric($discount)) && (is_numeric($basis))) {
  8883. if (($investment <= 0) || ($discount <= 0)) {
  8884. return self::$_errorCodes['num'];
  8885. }
  8886. $daysBetweenSettlementAndMaturity = self::YEARFRAC($settlement, $maturity, $basis);
  8887. if (!is_numeric($daysBetweenSettlementAndMaturity)) {
  8888. return $daysBetweenSettlementAndMaturity;
  8889. }
  8890. return $investment / ( 1 - ($discount * $daysBetweenSettlementAndMaturity));
  8891. }
  8892. return self::$_errorCodes['value'];
  8893. } // function RECEIVED()
  8894. /**
  8895. * INTRATE
  8896. *
  8897. * Returns the interest rate for a fully invested security.
  8898. *
  8899. * @param mixed settlement The security's settlement date.
  8900. * The security settlement date is the date after the issue date when the security is traded to the buyer.
  8901. * @param mixed maturity The security's maturity date.
  8902. * The maturity date is the date when the security expires.
  8903. * @param int investment The amount invested in the security.
  8904. * @param int redemption The amount to be received at maturity.
  8905. * @param int basis The type of day count to use.
  8906. * 0 or omitted US (NASD) 30/360
  8907. * 1 Actual/actual
  8908. * 2 Actual/360
  8909. * 3 Actual/365
  8910. * 4 European 30/360
  8911. * @return float
  8912. */
  8913. public static function INTRATE($settlement, $maturity, $investment, $redemption, $basis=0) {
  8914. $settlement = self::flattenSingleValue($settlement);
  8915. $maturity = self::flattenSingleValue($maturity);
  8916. $investment = (float) self::flattenSingleValue($investment);
  8917. $redemption = (float) self::flattenSingleValue($redemption);
  8918. $basis = (int) self::flattenSingleValue($basis);
  8919. // Validate
  8920. if ((is_numeric($investment)) && (is_numeric($redemption)) && (is_numeric($basis))) {
  8921. if (($investment <= 0) || ($redemption <= 0)) {
  8922. return self::$_errorCodes['num'];
  8923. }
  8924. $daysBetweenSettlementAndMaturity = self::YEARFRAC($settlement, $maturity, $basis);
  8925. if (!is_numeric($daysBetweenSettlementAndMaturity)) {
  8926. return $daysBetweenSettlementAndMaturity;
  8927. }
  8928. return (($redemption / $investment) - 1) / ($daysBetweenSettlementAndMaturity);
  8929. }
  8930. return self::$_errorCodes['value'];
  8931. } // function INTRATE()
  8932. /**
  8933. * TBILLEQ
  8934. *
  8935. * Returns the bond-equivalent yield for a Treasury bill.
  8936. *
  8937. * @param mixed settlement The Treasury bill's settlement date.
  8938. * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
  8939. * @param mixed maturity The Treasury bill's maturity date.
  8940. * The maturity date is the date when the Treasury bill expires.
  8941. * @param int discount The Treasury bill's discount rate.
  8942. * @return float
  8943. */
  8944. public static function TBILLEQ($settlement, $maturity, $discount) {
  8945. $settlement = self::flattenSingleValue($settlement);
  8946. $maturity = self::flattenSingleValue($maturity);
  8947. $discount = self::flattenSingleValue($discount);
  8948. // Use TBILLPRICE for validation
  8949. $testValue = self::TBILLPRICE($settlement, $maturity, $discount);
  8950. if (is_string($testValue)) {
  8951. return $testValue;
  8952. }
  8953. if (is_string($maturity = self::_getDateValue($maturity))) {
  8954. return self::$_errorCodes['value'];
  8955. }
  8956. if (self::$compatibilityMode == self::COMPATIBILITY_OPENOFFICE) {
  8957. ++$maturity;
  8958. $daysBetweenSettlementAndMaturity = self::YEARFRAC($settlement, $maturity) * 360;
  8959. } else {
  8960. $daysBetweenSettlementAndMaturity = (self::_getDateValue($maturity) - self::_getDateValue($settlement));
  8961. }
  8962. return (365 * $discount) / (360 - $discount * $daysBetweenSettlementAndMaturity);
  8963. } // function TBILLEQ()
  8964. /**
  8965. * TBILLPRICE
  8966. *
  8967. * Returns the yield for a Treasury bill.
  8968. *
  8969. * @param mixed settlement The Treasury bill's settlement date.
  8970. * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
  8971. * @param mixed maturity The Treasury bill's maturity date.
  8972. * The maturity date is the date when the Treasury bill expires.
  8973. * @param int discount The Treasury bill's discount rate.
  8974. * @return float
  8975. */
  8976. public static function TBILLPRICE($settlement, $maturity, $discount) {
  8977. $settlement = self::flattenSingleValue($settlement);
  8978. $maturity = self::flattenSingleValue($maturity);
  8979. $discount = self::flattenSingleValue($discount);
  8980. if (is_string($maturity = self::_getDateValue($maturity))) {
  8981. return self::$_errorCodes['value'];
  8982. }
  8983. // Validate
  8984. if (is_numeric($discount)) {
  8985. if ($discount <= 0) {
  8986. return self::$_errorCodes['num'];
  8987. }
  8988. if (self::$compatibilityMode == self::COMPATIBILITY_OPENOFFICE) {
  8989. ++$maturity;
  8990. $daysBetweenSettlementAndMaturity = self::YEARFRAC($settlement, $maturity) * 360;
  8991. if (!is_numeric($daysBetweenSettlementAndMaturity)) {
  8992. return $daysBetweenSettlementAndMaturity;
  8993. }
  8994. } else {
  8995. $daysBetweenSettlementAndMaturity = (self::_getDateValue($maturity) - self::_getDateValue($settlement));
  8996. }
  8997. if ($daysBetweenSettlementAndMaturity > 360) {
  8998. return self::$_errorCodes['num'];
  8999. }
  9000. $price = 100 * (1 - (($discount * $daysBetweenSettlementAndMaturity) / 360));
  9001. if ($price <= 0) {
  9002. return self::$_errorCodes['num'];
  9003. }
  9004. return $price;
  9005. }
  9006. return self::$_errorCodes['value'];
  9007. } // function TBILLPRICE()
  9008. /**
  9009. * TBILLYIELD
  9010. *
  9011. * Returns the yield for a Treasury bill.
  9012. *
  9013. * @param mixed settlement The Treasury bill's settlement date.
  9014. * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
  9015. * @param mixed maturity The Treasury bill's maturity date.
  9016. * The maturity date is the date when the Treasury bill expires.
  9017. * @param int price The Treasury bill's price per $100 face value.
  9018. * @return float
  9019. */
  9020. public static function TBILLYIELD($settlement, $maturity, $price) {
  9021. $settlement = self::flattenSingleValue($settlement);
  9022. $maturity = self::flattenSingleValue($maturity);
  9023. $price = self::flattenSingleValue($price);
  9024. // Validate
  9025. if (is_numeric($price)) {
  9026. if ($price <= 0) {
  9027. return self::$_errorCodes['num'];
  9028. }
  9029. if (self::$compatibilityMode == self::COMPATIBILITY_OPENOFFICE) {
  9030. ++$maturity;
  9031. $daysBetweenSettlementAndMaturity = self::YEARFRAC($settlement, $maturity) * 360;
  9032. if (!is_numeric($daysBetweenSettlementAndMaturity)) {
  9033. return $daysBetweenSettlementAndMaturity;
  9034. }
  9035. } else {
  9036. $daysBetweenSettlementAndMaturity = (self::_getDateValue($maturity) - self::_getDateValue($settlement));
  9037. }
  9038. if ($daysBetweenSettlementAndMaturity > 360) {
  9039. return self::$_errorCodes['num'];
  9040. }
  9041. return ((100 - $price) / $price) * (360 / $daysBetweenSettlementAndMaturity);
  9042. }
  9043. return self::$_errorCodes['value'];
  9044. } // function TBILLYIELD()
  9045. /**
  9046. * SLN
  9047. *
  9048. * Returns the straight-line depreciation of an asset for one period
  9049. *
  9050. * @param cost Initial cost of the asset
  9051. * @param salvage Value at the end of the depreciation
  9052. * @param life Number of periods over which the asset is depreciated
  9053. * @return float
  9054. */
  9055. public static function SLN($cost, $salvage, $life) {
  9056. $cost = self::flattenSingleValue($cost);
  9057. $salvage = self::flattenSingleValue($salvage);
  9058. $life = self::flattenSingleValue($life);
  9059. // Calculate
  9060. if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life))) {
  9061. if ($life < 0) {
  9062. return self::$_errorCodes['num'];
  9063. }
  9064. return ($cost - $salvage) / $life;
  9065. }
  9066. return self::$_errorCodes['value'];
  9067. } // function SLN()
  9068. /**
  9069. * YIELDMAT
  9070. *
  9071. * Returns the annual yield of a security that pays interest at maturity.
  9072. *
  9073. * @param mixed settlement The security's settlement date.
  9074. * The security's settlement date is the date after the issue date when the security is traded to the buyer.
  9075. * @param mixed maturity The security's maturity date.
  9076. * The maturity date is the date when the security expires.
  9077. * @param mixed issue The security's issue date.
  9078. * @param int rate The security's interest rate at date of issue.
  9079. * @param int price The security's price per $100 face value.
  9080. * @param int basis The type of day count to use.
  9081. * 0 or omitted US (NASD) 30/360
  9082. * 1 Actual/actual
  9083. * 2 Actual/360
  9084. * 3 Actual/365
  9085. * 4 European 30/360
  9086. * @return float
  9087. */
  9088. public static function YIELDMAT($settlement, $maturity, $issue, $rate, $price, $basis=0) {
  9089. $settlement = self::flattenSingleValue($settlement);
  9090. $maturity = self::flattenSingleValue($maturity);
  9091. $issue = self::flattenSingleValue($issue);
  9092. $rate = self::flattenSingleValue($rate);
  9093. $price = self::flattenSingleValue($price);
  9094. $basis = (int) self::flattenSingleValue($basis);
  9095. // Validate
  9096. if (is_numeric($rate) && is_numeric($price)) {
  9097. if (($rate <= 0) || ($price <= 0)) {
  9098. return self::$_errorCodes['num'];
  9099. }
  9100. $daysPerYear = self::_daysPerYear(self::YEAR($settlement),$basis);
  9101. if (!is_numeric($daysPerYear)) {
  9102. return $daysPerYear;
  9103. }
  9104. $daysBetweenIssueAndSettlement = self::YEARFRAC($issue, $settlement, $basis);
  9105. if (!is_numeric($daysBetweenIssueAndSettlement)) {
  9106. return $daysBetweenIssueAndSettlement;
  9107. }
  9108. $daysBetweenIssueAndSettlement *= $daysPerYear;
  9109. $daysBetweenIssueAndMaturity = self::YEARFRAC($issue, $maturity, $basis);
  9110. if (!is_numeric($daysBetweenIssueAndMaturity)) {
  9111. return $daysBetweenIssueAndMaturity;
  9112. }
  9113. $daysBetweenIssueAndMaturity *= $daysPerYear;
  9114. $daysBetweenSettlementAndMaturity = self::YEARFRAC($settlement, $maturity, $basis);
  9115. if (!is_numeric($daysBetweenSettlementAndMaturity)) {
  9116. return $daysBetweenSettlementAndMaturity;
  9117. }
  9118. $daysBetweenSettlementAndMaturity *= $daysPerYear;
  9119. return ((1 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate) - (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) /
  9120. (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) *
  9121. ($daysPerYear / $daysBetweenSettlementAndMaturity);
  9122. }
  9123. return self::$_errorCodes['value'];
  9124. } // function YIELDMAT()
  9125. /**
  9126. * YIELDDISC
  9127. *
  9128. * Returns the annual yield of a security that pays interest at maturity.
  9129. *
  9130. * @param mixed settlement The security's settlement date.
  9131. * The security's settlement date is the date after the issue date when the security is traded to the buyer.
  9132. * @param mixed maturity The security's maturity date.
  9133. * The maturity date is the date when the security expires.
  9134. * @param int price The security's price per $100 face value.
  9135. * @param int redemption The security's redemption value per $100 face value.
  9136. * @param int basis The type of day count to use.
  9137. * 0 or omitted US (NASD) 30/360
  9138. * 1 Actual/actual
  9139. * 2 Actual/360
  9140. * 3 Actual/365
  9141. * 4 European 30/360
  9142. * @return float
  9143. */
  9144. public static function YIELDDISC($settlement, $maturity, $price, $redemption, $basis=0) {
  9145. $settlement = self::flattenSingleValue($settlement);
  9146. $maturity = self::flattenSingleValue($maturity);
  9147. $price = self::flattenSingleValue($price);
  9148. $redemption = self::flattenSingleValue($redemption);
  9149. $basis = (int) self::flattenSingleValue($basis);
  9150. // Validate
  9151. if (is_numeric($price) && is_numeric($redemption)) {
  9152. if (($price <= 0) || ($redemption <= 0)) {
  9153. return self::$_errorCodes['num'];
  9154. }
  9155. $daysPerYear = self::_daysPerYear(self::YEAR($settlement),$basis);
  9156. if (!is_numeric($daysPerYear)) {
  9157. return $daysPerYear;
  9158. }
  9159. $daysBetweenSettlementAndMaturity = self::YEARFRAC($settlement, $maturity,$basis);
  9160. if (!is_numeric($daysBetweenSettlementAndMaturity)) {
  9161. return $daysBetweenSettlementAndMaturity;
  9162. }
  9163. $daysBetweenSettlementAndMaturity *= $daysPerYear;
  9164. return (($redemption - $price) / $price) * ($daysPerYear / $daysBetweenSettlementAndMaturity);
  9165. }
  9166. return self::$_errorCodes['value'];
  9167. } // function YIELDDISC()
  9168. /**
  9169. * CELL_ADDRESS
  9170. *
  9171. * Creates a cell address as text, given specified row and column numbers.
  9172. *
  9173. * @param row Row number to use in the cell reference
  9174. * @param column Column number to use in the cell reference
  9175. * @param relativity Flag indicating the type of reference to return
  9176. * 1 or omitted Absolute
  9177. * 2 Absolute row; relative column
  9178. * 3 Relative row; absolute column
  9179. * 4 Relative
  9180. * @param referenceStyle A logical value that specifies the A1 or R1C1 reference style.
  9181. * TRUE or omitted CELL_ADDRESS returns an A1-style reference
  9182. * FALSE CELL_ADDRESS returns an R1C1-style reference
  9183. * @param sheetText Optional Name of worksheet to use
  9184. * @return string
  9185. */
  9186. public static function CELL_ADDRESS($row, $column, $relativity=1, $referenceStyle=True, $sheetText='') {
  9187. $row = self::flattenSingleValue($row);
  9188. $column = self::flattenSingleValue($column);
  9189. $relativity = self::flattenSingleValue($relativity);
  9190. $sheetText = self::flattenSingleValue($sheetText);
  9191. if (($row < 1) || ($column < 1)) {
  9192. return self::$_errorCodes['value'];
  9193. }
  9194. if ($sheetText > '') {
  9195. if (strpos($sheetText,' ') !== False) { $sheetText = "'".$sheetText."'"; }
  9196. $sheetText .='!';
  9197. }
  9198. if ((!is_bool($referenceStyle)) || $referenceStyle) {
  9199. $rowRelative = $columnRelative = '$';
  9200. $column = PHPExcel_Cell::stringFromColumnIndex($column-1);
  9201. if (($relativity == 2) || ($relativity == 4)) { $columnRelative = ''; }
  9202. if (($relativity == 3) || ($relativity == 4)) { $rowRelative = ''; }
  9203. return $sheetText.$columnRelative.$column.$rowRelative.$row;
  9204. } else {
  9205. if (($relativity == 2) || ($relativity == 4)) { $column = '['.$column.']'; }
  9206. if (($relativity == 3) || ($relativity == 4)) { $row = '['.$row.']'; }
  9207. return $sheetText.'R'.$row.'C'.$column;
  9208. }
  9209. } // function CELL_ADDRESS()
  9210. /**
  9211. * COLUMN
  9212. *
  9213. * Returns the column number of the given cell reference
  9214. * If the cell reference is a range of cells, COLUMN returns the column numbers of each column in the reference as a horizontal array.
  9215. * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
  9216. * reference of the cell in which the COLUMN function appears; otherwise this function returns 0.
  9217. *
  9218. * @param cellAddress A reference to a range of cells for which you want the column numbers
  9219. * @return integer or array of integer
  9220. */
  9221. public static function COLUMN($cellAddress=Null) {
  9222. if (is_null($cellAddress) || trim($cellAddress) === '') { return 0; }
  9223. if (is_array($cellAddress)) {
  9224. foreach($cellAddress as $columnKey => $value) {
  9225. $columnKey = preg_replace('/[^a-z]/i','',$columnKey);
  9226. return (integer) PHPExcel_Cell::columnIndexFromString($columnKey);
  9227. }
  9228. } else {
  9229. if (strpos($cellAddress,'!') !== false) {
  9230. list($sheet,$cellAddress) = explode('!',$cellAddress);
  9231. }
  9232. if (strpos($cellAddress,':') !== false) {
  9233. list($startAddress,$endAddress) = explode(':',$cellAddress);
  9234. $startAddress = preg_replace('/[^a-z]/i','',$startAddress);
  9235. $endAddress = preg_replace('/[^a-z]/i','',$endAddress);
  9236. $returnValue = array();
  9237. do {
  9238. $returnValue[] = (integer) PHPExcel_Cell::columnIndexFromString($startAddress);
  9239. } while ($startAddress++ != $endAddress);
  9240. return $returnValue;
  9241. } else {
  9242. $cellAddress = preg_replace('/[^a-z]/i','',$cellAddress);
  9243. return (integer) PHPExcel_Cell::columnIndexFromString($cellAddress);
  9244. }
  9245. }
  9246. } // function COLUMN()
  9247. /**
  9248. * COLUMNS
  9249. *
  9250. * Returns the number of columns in an array or reference.
  9251. *
  9252. * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of columns
  9253. * @return integer
  9254. */
  9255. public static function COLUMNS($cellAddress=Null) {
  9256. if (is_null($cellAddress) || $cellAddress === '') {
  9257. return 1;
  9258. } elseif (!is_array($cellAddress)) {
  9259. return self::$_errorCodes['value'];
  9260. }
  9261. $isMatrix = (is_numeric(array_shift(array_keys($cellAddress))));
  9262. list($columns,$rows) = PHPExcel_Calculation::_getMatrixDimensions($cellAddress);
  9263. if ($isMatrix) {
  9264. return $rows;
  9265. } else {
  9266. return $columns;
  9267. }
  9268. } // function COLUMNS()
  9269. /**
  9270. * ROW
  9271. *
  9272. * Returns the row number of the given cell reference
  9273. * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference as a vertical array.
  9274. * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
  9275. * reference of the cell in which the ROW function appears; otherwise this function returns 0.
  9276. *
  9277. * @param cellAddress A reference to a range of cells for which you want the row numbers
  9278. * @return integer or array of integer
  9279. */
  9280. public static function ROW($cellAddress=Null) {
  9281. if (is_null($cellAddress) || trim($cellAddress) === '') { return 0; }
  9282. if (is_array($cellAddress)) {
  9283. foreach($cellAddress as $columnKey => $rowValue) {
  9284. foreach($rowValue as $rowKey => $cellValue) {
  9285. return (integer) preg_replace('/[^0-9]/i','',$rowKey);
  9286. }
  9287. }
  9288. } else {
  9289. if (strpos($cellAddress,'!') !== false) {
  9290. list($sheet,$cellAddress) = explode('!',$cellAddress);
  9291. }
  9292. if (strpos($cellAddress,':') !== false) {
  9293. list($startAddress,$endAddress) = explode(':',$cellAddress);
  9294. $startAddress = preg_replace('/[^0-9]/','',$startAddress);
  9295. $endAddress = preg_replace('/[^0-9]/','',$endAddress);
  9296. $returnValue = array();
  9297. do {
  9298. $returnValue[][] = (integer) $startAddress;
  9299. } while ($startAddress++ != $endAddress);
  9300. return $returnValue;
  9301. } else {
  9302. list($cellAddress) = explode(':',$cellAddress);
  9303. return (integer) preg_replace('/[^0-9]/','',$cellAddress);
  9304. }
  9305. }
  9306. } // function ROW()
  9307. /**
  9308. * ROWS
  9309. *
  9310. * Returns the number of rows in an array or reference.
  9311. *
  9312. * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of rows
  9313. * @return integer
  9314. */
  9315. public static function ROWS($cellAddress=Null) {
  9316. if (is_null($cellAddress) || $cellAddress === '') {
  9317. return 1;
  9318. } elseif (!is_array($cellAddress)) {
  9319. return self::$_errorCodes['value'];
  9320. }
  9321. $isMatrix = (is_numeric(array_shift(array_keys($cellAddress))));
  9322. list($columns,$rows) = PHPExcel_Calculation::_getMatrixDimensions($cellAddress);
  9323. if ($isMatrix) {
  9324. return $columns;
  9325. } else {
  9326. return $rows;
  9327. }
  9328. } // function ROWS()
  9329. /**
  9330. * INDIRECT
  9331. *
  9332. * Returns the number of rows in an array or reference.
  9333. *
  9334. * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of rows
  9335. * @return integer
  9336. */
  9337. public static function INDIRECT($cellAddress=Null, PHPExcel_Cell $pCell = null) {
  9338. $cellAddress = self::flattenSingleValue($cellAddress);
  9339. if (is_null($cellAddress) || $cellAddress === '') {
  9340. return self::REF();
  9341. }
  9342. $cellAddress1 = $cellAddress;
  9343. $cellAddress2 = NULL;
  9344. if (strpos($cellAddress,':') !== false) {
  9345. list($cellAddress1,$cellAddress2) = explode(':',$cellAddress);
  9346. }
  9347. if ((!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress1, $matches)) ||
  9348. ((!is_null($cellAddress2)) && (!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress2, $matches)))) {
  9349. return self::REF();
  9350. }
  9351. if (strpos($cellAddress,'!') !== false) {
  9352. list($sheetName,$cellAddress) = explode('!',$cellAddress);
  9353. $pSheet = $pCell->getParent()->getParent()->getSheetByName($sheetName);
  9354. } else {
  9355. $pSheet = $pCell->getParent();
  9356. }
  9357. return PHPExcel_Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, False);
  9358. } // function INDIRECT()
  9359. /**
  9360. * OFFSET
  9361. *
  9362. * Returns a reference to a range that is a specified number of rows and columns from a cell or range of cells.
  9363. * The reference that is returned can be a single cell or a range of cells. You can specify the number of rows and
  9364. * the number of columns to be returned.
  9365. *
  9366. * @param cellAddress The reference from which you want to base the offset. Reference must refer to a cell or
  9367. * range of adjacent cells; otherwise, OFFSET returns the #VALUE! error value.
  9368. * @param rows The number of rows, up or down, that you want the upper-left cell to refer to.
  9369. * Using 5 as the rows argument specifies that the upper-left cell in the reference is
  9370. * five rows below reference. Rows can be positive (which means below the starting reference)
  9371. * or negative (which means above the starting reference).
  9372. * @param cols The number of columns, to the left or right, that you want the upper-left cell of the result
  9373. * to refer to. Using 5 as the cols argument specifies that the upper-left cell in the
  9374. * reference is five columns to the right of reference. Cols can be positive (which means
  9375. * to the right of the starting reference) or negative (which means to the left of the
  9376. * starting reference).
  9377. * @param height The height, in number of rows, that you want the returned reference to be. Height must be a positive number.
  9378. * @param width The width, in number of columns, that you want the returned reference to be. Width must be a positive number.
  9379. * @return string A reference to a cell or range of cells
  9380. */
  9381. public static function OFFSET($cellAddress=Null,$rows=0,$columns=0,$height=null,$width=null) {
  9382. if ($cellAddress == Null) {
  9383. return 0;
  9384. }
  9385. $pCell = array_pop(func_get_args());
  9386. if (!is_object($pCell)) {
  9387. return self::$_errorCodes['reference'];
  9388. }
  9389. $sheetName = null;
  9390. if (strpos($cellAddress,"!")) {
  9391. list($sheetName,$cellAddress) = explode("!",$cellAddress);
  9392. }
  9393. if (strpos($cellAddress,":")) {
  9394. list($startCell,$endCell) = explode(":",$cellAddress);
  9395. } else {
  9396. $startCell = $endCell = $cellAddress;
  9397. }
  9398. list($startCellColumn,$startCellRow) = PHPExcel_Cell::coordinateFromString($startCell);
  9399. list($endCellColumn,$endCellRow) = PHPExcel_Cell::coordinateFromString($endCell);
  9400. $startCellRow += $rows;
  9401. $startCellColumn = PHPExcel_Cell::columnIndexFromString($startCellColumn) - 1;
  9402. $startCellColumn += $columns;
  9403. if (($startCellRow <= 0) || ($startCellColumn < 0)) {
  9404. return self::$_errorCodes['reference'];
  9405. }
  9406. $endCellColumn = PHPExcel_Cell::columnIndexFromString($endCellColumn) - 1;
  9407. if (($width != null) && (!is_object($width))) {
  9408. $endCellColumn = $startCellColumn + $width - 1;
  9409. } else {
  9410. $endCellColumn += $columns;
  9411. }
  9412. $startCellColumn = PHPExcel_Cell::stringFromColumnIndex($startCellColumn);
  9413. if (($height != null) && (!is_object($height))) {
  9414. $endCellRow = $startCellRow + $height - 1;
  9415. } else {
  9416. $endCellRow += $rows;
  9417. }
  9418. if (($endCellRow <= 0) || ($endCellColumn < 0)) {
  9419. return self::$_errorCodes['reference'];
  9420. }
  9421. $endCellColumn = PHPExcel_Cell::stringFromColumnIndex($endCellColumn);
  9422. $cellAddress = $startCellColumn.$startCellRow;
  9423. if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) {
  9424. $cellAddress .= ':'.$endCellColumn.$endCellRow;
  9425. }
  9426. if ($sheetName !== null) {
  9427. $pSheet = $pCell->getParent()->getParent()->getSheetByName($sheetName);
  9428. } else {
  9429. $pSheet = $pCell->getParent();
  9430. }
  9431. return PHPExcel_Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, False);
  9432. } // function OFFSET()
  9433. public static function CHOOSE() {
  9434. $chooseArgs = func_get_args();
  9435. $chosenEntry = self::flattenArray(array_shift($chooseArgs));
  9436. $entryCount = count($chooseArgs) - 1;
  9437. if(is_array($chosenEntry)) {
  9438. $chosenEntry = array_shift($chosenEntry);
  9439. }
  9440. if ((is_numeric($chosenEntry)) && (!is_bool($chosenEntry))) {
  9441. --$chosenEntry;
  9442. } else {
  9443. return self::$_errorCodes['value'];
  9444. }
  9445. $chosenEntry = floor($chosenEntry);
  9446. if (($chosenEntry <= 0) || ($chosenEntry > $entryCount)) {
  9447. return self::$_errorCodes['value'];
  9448. }
  9449. if (is_array($chooseArgs[$chosenEntry])) {
  9450. return self::flattenArray($chooseArgs[$chosenEntry]);
  9451. } else {
  9452. return $chooseArgs[$chosenEntry];
  9453. }
  9454. } // function CHOOSE()
  9455. /**
  9456. * MATCH
  9457. *
  9458. * The MATCH function searches for a specified item in a range of cells
  9459. *
  9460. * @param lookup_value The value that you want to match in lookup_array
  9461. * @param lookup_array The range of cells being searched
  9462. * @param match_type The number -1, 0, or 1. -1 means above, 0 means exact match, 1 means below. If match_type is 1 or -1, the list has to be ordered.
  9463. * @return integer The relative position of the found item
  9464. */
  9465. public static function MATCH($lookup_value, $lookup_array, $match_type=1) {
  9466. // flatten the lookup_array
  9467. $lookup_array = self::flattenArray($lookup_array);
  9468. // flatten lookup_value since it may be a cell reference to a value or the value itself
  9469. $lookup_value = self::flattenSingleValue($lookup_value);
  9470. // MATCH is not case sensitive
  9471. $lookup_value = strtolower($lookup_value);
  9472. /*
  9473. echo "--------------------<br>looking for $lookup_value in <br>";
  9474. print_r($lookup_array);
  9475. echo "<br>";
  9476. //return 1;
  9477. /**/
  9478. // **
  9479. // check inputs
  9480. // **
  9481. // lookup_value type has to be number, text, or logical values
  9482. if (!is_numeric($lookup_value) && !is_string($lookup_value) && !is_bool($lookup_value)){
  9483. // error: lookup_array should contain only number, text, or logical values
  9484. //echo "error: lookup_array should contain only number, text, or logical values<br>";
  9485. return self::$_errorCodes['na'];
  9486. }
  9487. // match_type is 0, 1 or -1
  9488. if ($match_type!==0 && $match_type!==-1 && $match_type!==1){
  9489. // error: wrong value for match_type
  9490. //echo "error: wrong value for match_type<br>";
  9491. return self::$_errorCodes['na'];
  9492. }
  9493. // lookup_array should not be empty
  9494. if (sizeof($lookup_array)<=0){
  9495. // error: empty range
  9496. //echo "error: empty range ".sizeof($lookup_array)."<br>";
  9497. return self::$_errorCodes['na'];
  9498. }
  9499. // lookup_array should contain only number, text, or logical values
  9500. for ($i=0;$i<sizeof($lookup_array);++$i){
  9501. // check the type of the value
  9502. if (!is_numeric($lookup_array[$i]) && !is_string($lookup_array[$i]) && !is_bool($lookup_array[$i])){
  9503. // error: lookup_array should contain only number, text, or logical values
  9504. //echo "error: lookup_array should contain only number, text, or logical values<br>";
  9505. return self::$_errorCodes['na'];
  9506. }
  9507. // convert tpo lowercase
  9508. if (is_string($lookup_array[$i]))
  9509. $lookup_array[$i] = strtolower($lookup_array[$i]);
  9510. }
  9511. // if match_type is 1 or -1, the list has to be ordered
  9512. if($match_type==1 || $match_type==-1){
  9513. // **
  9514. // iniitialization
  9515. // store the last value
  9516. $iLastValue=$lookup_array[0];
  9517. // **
  9518. // loop on the cells
  9519. for ($i=0;$i<sizeof($lookup_array);++$i){
  9520. // check ascending order
  9521. if(($match_type==1 && $lookup_array[$i]<$iLastValue)
  9522. // OR check descending order
  9523. || ($match_type==-1 && $lookup_array[$i]>$iLastValue)){
  9524. // error: list is not ordered correctly
  9525. //echo "error: list is not ordered correctly<br>";
  9526. return self::$_errorCodes['na'];
  9527. }
  9528. }
  9529. }
  9530. // **
  9531. // find the match
  9532. // **
  9533. // loop on the cells
  9534. for ($i=0; $i < sizeof($lookup_array); ++$i){
  9535. // if match_type is 0 <=> find the first value that is exactly equal to lookup_value
  9536. if ($match_type==0 && $lookup_array[$i]==$lookup_value){
  9537. // this is the exact match
  9538. return $i+1;
  9539. }
  9540. // if match_type is -1 <=> find the smallest value that is greater than or equal to lookup_value
  9541. if ($match_type==-1 && $lookup_array[$i] < $lookup_value){
  9542. if ($i<1){
  9543. // 1st cell was allready smaller than the lookup_value
  9544. break;
  9545. }
  9546. else
  9547. // the previous cell was the match
  9548. return $i;
  9549. }
  9550. // if match_type is 1 <=> find the largest value that is less than or equal to lookup_value
  9551. if ($match_type==1 && $lookup_array[$i] > $lookup_value){
  9552. if ($i<1){
  9553. // 1st cell was allready bigger than the lookup_value
  9554. break;
  9555. }
  9556. else
  9557. // the previous cell was the match
  9558. return $i;
  9559. }
  9560. }
  9561. // unsuccessful in finding a match, return #N/A error value
  9562. //echo "unsuccessful in finding a match<br>";
  9563. return self::$_errorCodes['na'];
  9564. } // function MATCH()
  9565. /**
  9566. * Uses an index to choose a value from a reference or array
  9567. * implemented: Return the value of a specified cell or array of cells Array form
  9568. * not implemented: Return a reference to specified cells Reference form
  9569. *
  9570. * @param range_array a range of cells or an array constant
  9571. * @param row_num selects the row in array from which to return a value. If row_num is omitted, column_num is required.
  9572. * @param column_num selects the column in array from which to return a value. If column_num is omitted, row_num is required.
  9573. */
  9574. public static function INDEX($arrayValues,$rowNum = 0,$columnNum = 0) {
  9575. if (($rowNum < 0) || ($columnNum < 0)) {
  9576. return self::$_errorCodes['value'];
  9577. }
  9578. $rowKeys = array_keys($arrayValues);
  9579. $columnKeys = @array_keys($arrayValues[$rowKeys[0]]);
  9580. if ($columnNum > count($columnKeys)) {
  9581. return self::$_errorCodes['value'];
  9582. } elseif ($columnNum == 0) {
  9583. if ($rowNum == 0) {
  9584. return $arrayValues;
  9585. }
  9586. $rowNum = $rowKeys[--$rowNum];
  9587. $returnArray = array();
  9588. foreach($arrayValues as $arrayColumn) {
  9589. if (is_array($arrayColumn)) {
  9590. if (isset($arrayColumn[$rowNum])) {
  9591. $returnArray[] = $arrayColumn[$rowNum];
  9592. } else {
  9593. return $arrayValues[$rowNum];
  9594. }
  9595. } else {
  9596. return $arrayValues[$rowNum];
  9597. }
  9598. }
  9599. return $returnArray;
  9600. }
  9601. $columnNum = $columnKeys[--$columnNum];
  9602. if ($rowNum > count($rowKeys)) {
  9603. return self::$_errorCodes['value'];
  9604. } elseif ($rowNum == 0) {
  9605. return $arrayValues[$columnNum];
  9606. }
  9607. $rowNum = $rowKeys[--$rowNum];
  9608. return $arrayValues[$rowNum][$columnNum];
  9609. } // function INDEX()
  9610. /**
  9611. * SYD
  9612. *
  9613. * Returns the sum-of-years' digits depreciation of an asset for a specified period.
  9614. *
  9615. * @param cost Initial cost of the asset
  9616. * @param salvage Value at the end of the depreciation
  9617. * @param life Number of periods over which the asset is depreciated
  9618. * @param period Period
  9619. * @return float
  9620. */
  9621. public static function SYD($cost, $salvage, $life, $period) {
  9622. $cost = self::flattenSingleValue($cost);
  9623. $salvage = self::flattenSingleValue($salvage);
  9624. $life = self::flattenSingleValue($life);
  9625. $period = self::flattenSingleValue($period);
  9626. // Calculate
  9627. if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period))) {
  9628. if (($life < 1) || ($period > $life)) {
  9629. return self::$_errorCodes['num'];
  9630. }
  9631. return (($cost - $salvage) * ($life - $period + 1) * 2) / ($life * ($life + 1));
  9632. }
  9633. return self::$_errorCodes['value'];
  9634. } // function SYD()
  9635. /**
  9636. * TRANSPOSE
  9637. *
  9638. * @param array $matrixData A matrix of values
  9639. * @return array
  9640. *
  9641. * Unlike the Excel TRANSPOSE function, which will only work on a single row or column, this function will transpose a full matrix.
  9642. */
  9643. public static function TRANSPOSE($matrixData) {
  9644. $returnMatrix = array();
  9645. if (!is_array($matrixData)) { $matrixData = array(array($matrixData)); }
  9646. $column = 0;
  9647. foreach($matrixData as $matrixRow) {
  9648. $row = 0;
  9649. foreach($matrixRow as $matrixCell) {
  9650. $returnMatrix[$row][$column] = $matrixCell;
  9651. ++$row;
  9652. }
  9653. ++$column;
  9654. }
  9655. return $returnMatrix;
  9656. } // function TRANSPOSE()
  9657. /**
  9658. * MMULT
  9659. *
  9660. * @param array $matrixData1 A matrix of values
  9661. * @param array $matrixData2 A matrix of values
  9662. * @return array
  9663. */
  9664. public static function MMULT($matrixData1,$matrixData2) {
  9665. $matrixAData = $matrixBData = array();
  9666. if (!is_array($matrixData1)) { $matrixData1 = array(array($matrixData1)); }
  9667. if (!is_array($matrixData2)) { $matrixData2 = array(array($matrixData2)); }
  9668. $rowA = 0;
  9669. foreach($matrixData1 as $matrixRow) {
  9670. $columnA = 0;
  9671. foreach($matrixRow as $matrixCell) {
  9672. if ((is_string($matrixCell)) || ($matrixCell === null)) {
  9673. return self::$_errorCodes['value'];
  9674. }
  9675. $matrixAData[$rowA][$columnA] = $matrixCell;
  9676. ++$columnA;
  9677. }
  9678. ++$rowA;
  9679. }
  9680. try {
  9681. $matrixA = new Matrix($matrixAData);
  9682. $rowB = 0;
  9683. foreach($matrixData2 as $matrixRow) {
  9684. $columnB = 0;
  9685. foreach($matrixRow as $matrixCell) {
  9686. if ((is_string($matrixCell)) || ($matrixCell === null)) {
  9687. return self::$_errorCodes['value'];
  9688. }
  9689. $matrixBData[$rowB][$columnB] = $matrixCell;
  9690. ++$columnB;
  9691. }
  9692. ++$rowB;
  9693. }
  9694. $matrixB = new Matrix($matrixBData);
  9695. if (($rowA != $columnB) || ($rowB != $columnA)) {
  9696. return self::$_errorCodes['value'];
  9697. }
  9698. return $matrixA->times($matrixB)->getArray();
  9699. } catch (Exception $ex) {
  9700. return self::$_errorCodes['value'];
  9701. }
  9702. } // function MMULT()
  9703. /**
  9704. * MINVERSE
  9705. *
  9706. * @param array $matrixValues A matrix of values
  9707. * @return array
  9708. */
  9709. public static function MINVERSE($matrixValues) {
  9710. $matrixData = array();
  9711. if (!is_array($matrixValues)) { $matrixValues = array(array($matrixValues)); }
  9712. $row = $maxColumn = 0;
  9713. foreach($matrixValues as $matrixRow) {
  9714. $column = 0;
  9715. foreach($matrixRow as $matrixCell) {
  9716. if ((is_string($matrixCell)) || ($matrixCell === null)) {
  9717. return self::$_errorCodes['value'];
  9718. }
  9719. $matrixData[$column][$row] = $matrixCell;
  9720. ++$column;
  9721. }
  9722. if ($column > $maxColumn) { $maxColumn = $column; }
  9723. ++$row;
  9724. }
  9725. if ($row != $maxColumn) { return self::$_errorCodes['value']; }
  9726. try {
  9727. $matrix = new Matrix($matrixData);
  9728. return $matrix->inverse()->getArray();
  9729. } catch (Exception $ex) {
  9730. return self::$_errorCodes['value'];
  9731. }
  9732. } // function MINVERSE()
  9733. /**
  9734. * MDETERM
  9735. *
  9736. * @param array $matrixValues A matrix of values
  9737. * @return float
  9738. */
  9739. public static function MDETERM($matrixValues) {
  9740. $matrixData = array();
  9741. if (!is_array($matrixValues)) { $matrixValues = array(array($matrixValues)); }
  9742. $row = $maxColumn = 0;
  9743. foreach($matrixValues as $matrixRow) {
  9744. $column = 0;
  9745. foreach($matrixRow as $matrixCell) {
  9746. if ((is_string($matrixCell)) || ($matrixCell === null)) {
  9747. return self::$_errorCodes['value'];
  9748. }
  9749. $matrixData[$column][$row] = $matrixCell;
  9750. ++$column;
  9751. }
  9752. if ($column > $maxColumn) { $maxColumn = $column; }
  9753. ++$row;
  9754. }
  9755. if ($row != $maxColumn) { return self::$_errorCodes['value']; }
  9756. try {
  9757. $matrix = new Matrix($matrixData);
  9758. return $matrix->det();
  9759. } catch (Exception $ex) {
  9760. return self::$_errorCodes['value'];
  9761. }
  9762. } // function MDETERM()
  9763. /**
  9764. * SUMPRODUCT
  9765. *
  9766. * @param mixed $value Value to check
  9767. * @return float
  9768. */
  9769. public static function SUMPRODUCT() {
  9770. $arrayList = func_get_args();
  9771. $wrkArray = self::flattenArray(array_shift($arrayList));
  9772. $wrkCellCount = count($wrkArray);
  9773. foreach($arrayList as $matrixData) {
  9774. $array2 = self::flattenArray($matrixData);
  9775. $count = count($array2);
  9776. if ($wrkCellCount != $count) {
  9777. return self::$_errorCodes['value'];
  9778. }
  9779. foreach ($array2 as $i => $val) {
  9780. if (((is_numeric($wrkArray[$i])) && (!is_string($wrkArray[$i]))) &&
  9781. ((is_numeric($val)) && (!is_string($val)))) {
  9782. $wrkArray[$i] *= $val;
  9783. }
  9784. }
  9785. }
  9786. return array_sum($wrkArray);
  9787. } // function SUMPRODUCT()
  9788. /**
  9789. * SUMX2MY2
  9790. *
  9791. * @param mixed $value Value to check
  9792. * @return float
  9793. */
  9794. public static function SUMX2MY2($matrixData1,$matrixData2) {
  9795. $array1 = self::flattenArray($matrixData1);
  9796. $array2 = self::flattenArray($matrixData2);
  9797. $count1 = count($array1);
  9798. $count2 = count($array2);
  9799. if ($count1 < $count2) {
  9800. $count = $count1;
  9801. } else {
  9802. $count = $count2;
  9803. }
  9804. $result = 0;
  9805. for ($i = 0; $i < $count; ++$i) {
  9806. if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
  9807. ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
  9808. $result += ($array1[$i] * $array1[$i]) - ($array2[$i] * $array2[$i]);
  9809. }
  9810. }
  9811. return $result;
  9812. } // function SUMX2MY2()
  9813. /**
  9814. * SUMX2PY2
  9815. *
  9816. * @param mixed $value Value to check
  9817. * @return float
  9818. */
  9819. public static function SUMX2PY2($matrixData1,$matrixData2) {
  9820. $array1 = self::flattenArray($matrixData1);
  9821. $array2 = self::flattenArray($matrixData2);
  9822. $count1 = count($array1);
  9823. $count2 = count($array2);
  9824. if ($count1 < $count2) {
  9825. $count = $count1;
  9826. } else {
  9827. $count = $count2;
  9828. }
  9829. $result = 0;
  9830. for ($i = 0; $i < $count; ++$i) {
  9831. if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
  9832. ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
  9833. $result += ($array1[$i] * $array1[$i]) + ($array2[$i] * $array2[$i]);
  9834. }
  9835. }
  9836. return $result;
  9837. } // function SUMX2PY2()
  9838. /**
  9839. * SUMXMY2
  9840. *
  9841. * @param mixed $value Value to check
  9842. * @return float
  9843. */
  9844. public static function SUMXMY2($matrixData1,$matrixData2) {
  9845. $array1 = self::flattenArray($matrixData1);
  9846. $array2 = self::flattenArray($matrixData2);
  9847. $count1 = count($array1);
  9848. $count2 = count($array2);
  9849. if ($count1 < $count2) {
  9850. $count = $count1;
  9851. } else {
  9852. $count = $count2;
  9853. }
  9854. $result = 0;
  9855. for ($i = 0; $i < $count; ++$i) {
  9856. if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
  9857. ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
  9858. $result += ($array1[$i] - $array2[$i]) * ($array1[$i] - $array2[$i]);
  9859. }
  9860. }
  9861. return $result;
  9862. } // function SUMXMY2()
  9863. private static function _vlookupSort($a,$b) {
  9864. $firstColumn = array_shift(array_keys($a));
  9865. if (strtolower($a[$firstColumn]) == strtolower($b[$firstColumn])) {
  9866. return 0;
  9867. }
  9868. return (strtolower($a[$firstColumn]) < strtolower($b[$firstColumn])) ? -1 : 1;
  9869. } // function _vlookupSort()
  9870. /**
  9871. * VLOOKUP
  9872. * The VLOOKUP function searches for value in the left-most column of lookup_array and returns the value in the same row based on the index_number.
  9873. * @param lookup_value The value that you want to match in lookup_array
  9874. * @param lookup_array The range of cells being searched
  9875. * @param index_number The column number in table_array from which the matching value must be returned. The first column is 1.
  9876. * @param not_exact_match Determines if you are looking for an exact match based on lookup_value.
  9877. * @return mixed The value of the found cell
  9878. */
  9879. public static function VLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match=true) {
  9880. // index_number must be greater than or equal to 1
  9881. if ($index_number < 1) {
  9882. return self::$_errorCodes['value'];
  9883. }
  9884. // index_number must be less than or equal to the number of columns in lookup_array
  9885. if ((!is_array($lookup_array)) || (count($lookup_array) < 1)) {
  9886. return self::$_errorCodes['reference'];
  9887. } else {
  9888. $firstRow = array_pop(array_keys($lookup_array));
  9889. if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) {
  9890. return self::$_errorCodes['reference'];
  9891. } else {
  9892. $columnKeys = array_keys($lookup_array[$firstRow]);
  9893. $returnColumn = $columnKeys[--$index_number];
  9894. $firstColumn = array_shift($columnKeys);
  9895. }
  9896. }
  9897. if (!$not_exact_match) {
  9898. uasort($lookup_array,array('self','_vlookupSort'));
  9899. }
  9900. $rowNumber = $rowValue = False;
  9901. foreach($lookup_array as $rowKey => $rowData) {
  9902. if (strtolower($rowData[$firstColumn]) > strtolower($lookup_value)) {
  9903. break;
  9904. }
  9905. $rowNumber = $rowKey;
  9906. $rowValue = $rowData[$firstColumn];
  9907. }
  9908. if ($rowNumber !== false) {
  9909. if ((!$not_exact_match) && ($rowValue != $lookup_value)) {
  9910. // if an exact match is required, we have what we need to return an appropriate response
  9911. return self::$_errorCodes['na'];
  9912. } else {
  9913. // otherwise return the appropriate value
  9914. return $lookup_array[$rowNumber][$returnColumn];
  9915. }
  9916. }
  9917. return self::$_errorCodes['na'];
  9918. } // function VLOOKUP()
  9919. /**
  9920. * LOOKUP
  9921. * The LOOKUP function searches for value either from a one-row or one-column range or from an array.
  9922. * @param lookup_value The value that you want to match in lookup_array
  9923. * @param lookup_vector The range of cells being searched
  9924. * @param result_vector The column from which the matching value must be returned
  9925. * @return mixed The value of the found cell
  9926. */
  9927. public static function LOOKUP($lookup_value, $lookup_vector, $result_vector=null) {
  9928. $lookup_value = self::flattenSingleValue($lookup_value);
  9929. if (!is_array($lookup_vector)) {
  9930. return self::$_errorCodes['na'];
  9931. }
  9932. $lookupRows = count($lookup_vector);
  9933. $lookupColumns = count($lookup_vector[array_shift(array_keys($lookup_vector))]);
  9934. if ((($lookupRows == 1) && ($lookupColumns > 1)) || (($lookupRows == 2) && ($lookupColumns != 2))) {
  9935. $lookup_vector = self::TRANSPOSE($lookup_vector);
  9936. $lookupRows = count($lookup_vector);
  9937. $lookupColumns = count($lookup_vector[array_shift(array_keys($lookup_vector))]);
  9938. }
  9939. if (is_null($result_vector)) {
  9940. $result_vector = $lookup_vector;
  9941. }
  9942. $resultRows = count($result_vector);
  9943. $resultColumns = count($result_vector[array_shift(array_keys($result_vector))]);
  9944. if ((($resultRows == 1) && ($resultColumns > 1)) || (($resultRows == 2) && ($resultColumns != 2))) {
  9945. $result_vector = self::TRANSPOSE($result_vector);
  9946. $resultRows = count($result_vector);
  9947. $resultColumns = count($result_vector[array_shift(array_keys($result_vector))]);
  9948. }
  9949. if ($lookupRows == 2) {
  9950. $result_vector = array_pop($lookup_vector);
  9951. $lookup_vector = array_shift($lookup_vector);
  9952. }
  9953. if ($lookupColumns != 2) {
  9954. foreach($lookup_vector as &$value) {
  9955. if (is_array($value)) {
  9956. $key1 = $key2 = array_shift(array_keys($value));
  9957. $key2++;
  9958. $dataValue1 = $value[$key1];
  9959. } else {
  9960. $key1 = 0;
  9961. $key2 = 1;
  9962. $dataValue1 = $value;
  9963. }
  9964. $dataValue2 = array_shift($result_vector);
  9965. if (is_array($dataValue2)) {
  9966. $dataValue2 = array_shift($dataValue2);
  9967. }
  9968. $value = array($key1 => $dataValue1, $key2 => $dataValue2);
  9969. }
  9970. unset($value);
  9971. }
  9972. return self::VLOOKUP($lookup_value,$lookup_vector,2);
  9973. } // function LOOKUP()
  9974. /**
  9975. * Convert a multi-dimensional array to a simple 1-dimensional array
  9976. *
  9977. * @param array $array Array to be flattened
  9978. * @return array Flattened array
  9979. */
  9980. public static function flattenArray($array) {
  9981. if (!is_array($array)) {
  9982. return (array) $array;
  9983. }
  9984. $arrayValues = array();
  9985. foreach ($array as $value) {
  9986. if (is_array($value)) {
  9987. foreach ($value as $val) {
  9988. if (is_array($val)) {
  9989. foreach ($val as $v) {
  9990. $arrayValues[] = $v;
  9991. }
  9992. } else {
  9993. $arrayValues[] = $val;
  9994. }
  9995. }
  9996. } else {
  9997. $arrayValues[] = $value;
  9998. }
  9999. }
  10000. return $arrayValues;
  10001. } // function flattenArray()
  10002. /**
  10003. * Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing
  10004. *
  10005. * @param array $array Array to be flattened
  10006. * @return array Flattened array
  10007. */
  10008. public static function flattenArrayIndexed($array) {
  10009. if (!is_array($array)) {
  10010. return (array) $array;
  10011. }
  10012. $arrayValues = array();
  10013. foreach ($array as $k1 => $value) {
  10014. if (is_array($value)) {
  10015. foreach ($value as $k2 => $val) {
  10016. if (is_array($val)) {
  10017. foreach ($val as $k3 => $v) {
  10018. $arrayValues[$k1.'.'.$k2.'.'.$k3] = $v;
  10019. }
  10020. } else {
  10021. $arrayValues[$k1.'.'.$k2] = $val;
  10022. }
  10023. }
  10024. } else {
  10025. $arrayValues[$k1] = $value;
  10026. }
  10027. }
  10028. return $arrayValues;
  10029. } // function flattenArrayIndexed()
  10030. /**
  10031. * Convert an array to a single scalar value by extracting the first element
  10032. *
  10033. * @param mixed $value Array or scalar value
  10034. * @return mixed
  10035. */
  10036. public static function flattenSingleValue($value = '') {
  10037. if (is_array($value)) {
  10038. return self::flattenSingleValue(array_pop($value));
  10039. }
  10040. return $value;
  10041. } // function flattenSingleValue()
  10042. } // class PHPExcel_Calculation_Functions
  10043. //
  10044. // There are a few mathematical functions that aren't available on all versions of PHP for all platforms
  10045. // These functions aren't available in Windows implementations of PHP prior to version 5.3.0
  10046. // So we test if they do exist for this version of PHP/operating platform; and if not we create them
  10047. //
  10048. if (!function_exists('acosh')) {
  10049. function acosh($x) {
  10050. return 2 * log(sqrt(($x + 1) / 2) + sqrt(($x - 1) / 2));
  10051. } // function acosh()
  10052. }
  10053. if (!function_exists('asinh')) {
  10054. function asinh($x) {
  10055. return log($x + sqrt(1 + $x * $x));
  10056. } // function asinh()
  10057. }
  10058. if (!function_exists('atanh')) {
  10059. function atanh($x) {
  10060. return (log(1 + $x) - log(1 - $x)) / 2;
  10061. } // function atanh()
  10062. }
  10063. if (!function_exists('money_format')) {
  10064. function money_format($format, $number) {
  10065. $regex = array( '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?(?:#([0-9]+))?',
  10066. '(?:\.([0-9]+))?([in%])/'
  10067. );
  10068. $regex = implode('', $regex);
  10069. if (setlocale(LC_MONETARY, null) == '') {
  10070. setlocale(LC_MONETARY, '');
  10071. }
  10072. $locale = localeconv();
  10073. $number = floatval($number);
  10074. if (!preg_match($regex, $format, $fmatch)) {
  10075. trigger_error("No format specified or invalid format", E_USER_WARNING);
  10076. return $number;
  10077. }
  10078. $flags = array( 'fillchar' => preg_match('/\=(.)/', $fmatch[1], $match) ? $match[1] : ' ',
  10079. 'nogroup' => preg_match('/\^/', $fmatch[1]) > 0,
  10080. 'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ? $match[0] : '+',
  10081. 'nosimbol' => preg_match('/\!/', $fmatch[1]) > 0,
  10082. 'isleft' => preg_match('/\-/', $fmatch[1]) > 0
  10083. );
  10084. $width = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
  10085. $left = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
  10086. $right = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
  10087. $conversion = $fmatch[5];
  10088. $positive = true;
  10089. if ($number < 0) {
  10090. $positive = false;
  10091. $number *= -1;
  10092. }
  10093. $letter = $positive ? 'p' : 'n';
  10094. $prefix = $suffix = $cprefix = $csuffix = $signal = '';
  10095. if (!$positive) {
  10096. $signal = $locale['negative_sign'];
  10097. switch (true) {
  10098. case $locale['n_sign_posn'] == 0 || $flags['usesignal'] == '(':
  10099. $prefix = '(';
  10100. $suffix = ')';
  10101. break;
  10102. case $locale['n_sign_posn'] == 1:
  10103. $prefix = $signal;
  10104. break;
  10105. case $locale['n_sign_posn'] == 2:
  10106. $suffix = $signal;
  10107. break;
  10108. case $locale['n_sign_posn'] == 3:
  10109. $cprefix = $signal;
  10110. break;
  10111. case $locale['n_sign_posn'] == 4:
  10112. $csuffix = $signal;
  10113. break;
  10114. }
  10115. }
  10116. if (!$flags['nosimbol']) {
  10117. $currency = $cprefix;
  10118. $currency .= ($conversion == 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']);
  10119. $currency .= $csuffix;
  10120. $currency = iconv('ISO-8859-1','UTF-8',$currency);
  10121. } else {
  10122. $currency = '';
  10123. }
  10124. $space = $locale["{$letter}_sep_by_space"] ? ' ' : '';
  10125. $number = number_format($number, $right, $locale['mon_decimal_point'], $flags['nogroup'] ? '' : $locale['mon_thousands_sep'] );
  10126. $number = explode($locale['mon_decimal_point'], $number);
  10127. $n = strlen($prefix) + strlen($currency);
  10128. if ($left > 0 && $left > $n) {
  10129. if ($flags['isleft']) {
  10130. $number[0] .= str_repeat($flags['fillchar'], $left - $n);
  10131. } else {
  10132. $number[0] = str_repeat($flags['fillchar'], $left - $n) . $number[0];
  10133. }
  10134. }
  10135. $number = implode($locale['mon_decimal_point'], $number);
  10136. if ($locale["{$letter}_cs_precedes"]) {
  10137. $number = $prefix . $currency . $space . $number . $suffix;
  10138. } else {
  10139. $number = $prefix . $number . $space . $currency . $suffix;
  10140. }
  10141. if ($width > 0) {
  10142. $number = str_pad($number, $width, $flags['fillchar'], $flags['isleft'] ? STR_PAD_RIGHT : STR_PAD_LEFT);
  10143. }
  10144. $format = str_replace($fmatch[0], $number, $format);
  10145. return $format;
  10146. } // function money_format()
  10147. }
  10148. //
  10149. // Strangely, PHP doesn't have a mb_str_replace multibyte function
  10150. // As we'll only ever use this function with UTF-8 characters, we can simply "hard-code" the character set
  10151. //
  10152. if ((!function_exists('mb_str_replace')) &&
  10153. (function_exists('mb_substr')) && (function_exists('mb_strlen')) && (function_exists('mb_strpos'))) {
  10154. function mb_str_replace($search, $replace, $subject) {
  10155. if(is_array($subject)) {
  10156. $ret = array();
  10157. foreach($subject as $key => $val) {
  10158. $ret[$key] = mb_str_replace($search, $replace, $val);
  10159. }
  10160. return $ret;
  10161. }
  10162. foreach((array) $search as $key => $s) {
  10163. if($s == '') {
  10164. continue;
  10165. }
  10166. $r = !is_array($replace) ? $replace : (array_key_exists($key, $replace) ? $replace[$key] : '');
  10167. $pos = mb_strpos($subject, $s, 0, 'UTF-8');
  10168. while($pos !== false) {
  10169. $subject = mb_substr($subject, 0, $pos, 'UTF-8') . $r . mb_substr($subject, $pos + mb_strlen($s, 'UTF-8'), 65535, 'UTF-8');
  10170. $pos = mb_strpos($subject, $s, $pos + mb_strlen($r, 'UTF-8'), 'UTF-8');
  10171. }
  10172. }
  10173. return $subject;
  10174. }
  10175. }