Statistical.php 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651
  1. <?php
  2. namespace PhpOffice\PhpSpreadsheet\Calculation;
  3. use PhpOffice\PhpSpreadsheet\Shared\Trend\Trend;
  4. class Statistical
  5. {
  6. const LOG_GAMMA_X_MAX_VALUE = 2.55e305;
  7. const XMININ = 2.23e-308;
  8. const EPS = 2.22e-16;
  9. const MAX_VALUE = 1.2e308;
  10. const MAX_ITERATIONS = 256;
  11. const SQRT2PI = 2.5066282746310005024157652848110452530069867406099;
  12. private static function checkTrendArrays(&$array1, &$array2)
  13. {
  14. if (!is_array($array1)) {
  15. $array1 = [$array1];
  16. }
  17. if (!is_array($array2)) {
  18. $array2 = [$array2];
  19. }
  20. $array1 = Functions::flattenArray($array1);
  21. $array2 = Functions::flattenArray($array2);
  22. foreach ($array1 as $key => $value) {
  23. if ((is_bool($value)) || (is_string($value)) || ($value === null)) {
  24. unset($array1[$key], $array2[$key]);
  25. }
  26. }
  27. foreach ($array2 as $key => $value) {
  28. if ((is_bool($value)) || (is_string($value)) || ($value === null)) {
  29. unset($array1[$key], $array2[$key]);
  30. }
  31. }
  32. $array1 = array_merge($array1);
  33. $array2 = array_merge($array2);
  34. return true;
  35. }
  36. /**
  37. * Incomplete beta function.
  38. *
  39. * @author Jaco van Kooten
  40. * @author Paul Meagher
  41. *
  42. * The computation is based on formulas from Numerical Recipes, Chapter 6.4 (W.H. Press et al, 1992).
  43. *
  44. * @param mixed $x require 0<=x<=1
  45. * @param mixed $p require p>0
  46. * @param mixed $q require q>0
  47. *
  48. * @return float 0 if x<0, p<=0, q<=0 or p+q>2.55E305 and 1 if x>1 to avoid errors and over/underflow
  49. */
  50. private static function incompleteBeta($x, $p, $q)
  51. {
  52. if ($x <= 0.0) {
  53. return 0.0;
  54. } elseif ($x >= 1.0) {
  55. return 1.0;
  56. } elseif (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > self::LOG_GAMMA_X_MAX_VALUE)) {
  57. return 0.0;
  58. }
  59. $beta_gam = exp((0 - self::logBeta($p, $q)) + $p * log($x) + $q * log(1.0 - $x));
  60. if ($x < ($p + 1.0) / ($p + $q + 2.0)) {
  61. return $beta_gam * self::betaFraction($x, $p, $q) / $p;
  62. }
  63. return 1.0 - ($beta_gam * self::betaFraction(1 - $x, $q, $p) / $q);
  64. }
  65. // Function cache for logBeta function
  66. private static $logBetaCacheP = 0.0;
  67. private static $logBetaCacheQ = 0.0;
  68. private static $logBetaCacheResult = 0.0;
  69. /**
  70. * The natural logarithm of the beta function.
  71. *
  72. * @param mixed $p require p>0
  73. * @param mixed $q require q>0
  74. *
  75. * @return float 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow
  76. *
  77. * @author Jaco van Kooten
  78. */
  79. private static function logBeta($p, $q)
  80. {
  81. if ($p != self::$logBetaCacheP || $q != self::$logBetaCacheQ) {
  82. self::$logBetaCacheP = $p;
  83. self::$logBetaCacheQ = $q;
  84. if (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > self::LOG_GAMMA_X_MAX_VALUE)) {
  85. self::$logBetaCacheResult = 0.0;
  86. } else {
  87. self::$logBetaCacheResult = self::logGamma($p) + self::logGamma($q) - self::logGamma($p + $q);
  88. }
  89. }
  90. return self::$logBetaCacheResult;
  91. }
  92. /**
  93. * Evaluates of continued fraction part of incomplete beta function.
  94. * Based on an idea from Numerical Recipes (W.H. Press et al, 1992).
  95. *
  96. * @author Jaco van Kooten
  97. *
  98. * @param mixed $x
  99. * @param mixed $p
  100. * @param mixed $q
  101. *
  102. * @return float
  103. */
  104. private static function betaFraction($x, $p, $q)
  105. {
  106. $c = 1.0;
  107. $sum_pq = $p + $q;
  108. $p_plus = $p + 1.0;
  109. $p_minus = $p - 1.0;
  110. $h = 1.0 - $sum_pq * $x / $p_plus;
  111. if (abs($h) < self::XMININ) {
  112. $h = self::XMININ;
  113. }
  114. $h = 1.0 / $h;
  115. $frac = $h;
  116. $m = 1;
  117. $delta = 0.0;
  118. while ($m <= self::MAX_ITERATIONS && abs($delta - 1.0) > Functions::PRECISION) {
  119. $m2 = 2 * $m;
  120. // even index for d
  121. $d = $m * ($q - $m) * $x / (($p_minus + $m2) * ($p + $m2));
  122. $h = 1.0 + $d * $h;
  123. if (abs($h) < self::XMININ) {
  124. $h = self::XMININ;
  125. }
  126. $h = 1.0 / $h;
  127. $c = 1.0 + $d / $c;
  128. if (abs($c) < self::XMININ) {
  129. $c = self::XMININ;
  130. }
  131. $frac *= $h * $c;
  132. // odd index for d
  133. $d = -($p + $m) * ($sum_pq + $m) * $x / (($p + $m2) * ($p_plus + $m2));
  134. $h = 1.0 + $d * $h;
  135. if (abs($h) < self::XMININ) {
  136. $h = self::XMININ;
  137. }
  138. $h = 1.0 / $h;
  139. $c = 1.0 + $d / $c;
  140. if (abs($c) < self::XMININ) {
  141. $c = self::XMININ;
  142. }
  143. $delta = $h * $c;
  144. $frac *= $delta;
  145. ++$m;
  146. }
  147. return $frac;
  148. }
  149. /**
  150. * logGamma function.
  151. *
  152. * @version 1.1
  153. *
  154. * @author Jaco van Kooten
  155. *
  156. * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher.
  157. *
  158. * The natural logarithm of the gamma function. <br />
  159. * Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz <br />
  160. * Applied Mathematics Division <br />
  161. * Argonne National Laboratory <br />
  162. * Argonne, IL 60439 <br />
  163. * <p>
  164. * References:
  165. * <ol>
  166. * <li>W. J. Cody and K. E. Hillstrom, 'Chebyshev Approximations for the Natural
  167. * Logarithm of the Gamma Function,' Math. Comp. 21, 1967, pp. 198-203.</li>
  168. * <li>K. E. Hillstrom, ANL/AMD Program ANLC366S, DGAMMA/DLGAMA, May, 1969.</li>
  169. * <li>Hart, Et. Al., Computer Approximations, Wiley and sons, New York, 1968.</li>
  170. * </ol>
  171. * </p>
  172. * <p>
  173. * From the original documentation:
  174. * </p>
  175. * <p>
  176. * This routine calculates the LOG(GAMMA) function for a positive real argument X.
  177. * Computation is based on an algorithm outlined in references 1 and 2.
  178. * The program uses rational functions that theoretically approximate LOG(GAMMA)
  179. * to at least 18 significant decimal digits. The approximation for X > 12 is from
  180. * reference 3, while approximations for X < 12.0 are similar to those in reference
  181. * 1, but are unpublished. The accuracy achieved depends on the arithmetic system,
  182. * the compiler, the intrinsic functions, and proper selection of the
  183. * machine-dependent constants.
  184. * </p>
  185. * <p>
  186. * Error returns: <br />
  187. * The program returns the value XINF for X .LE. 0.0 or when overflow would occur.
  188. * The computation is believed to be free of underflow and overflow.
  189. * </p>
  190. *
  191. * @return float MAX_VALUE for x < 0.0 or when overflow would occur, i.e. x > 2.55E305
  192. */
  193. // Function cache for logGamma
  194. private static $logGammaCacheResult = 0.0;
  195. private static $logGammaCacheX = 0.0;
  196. private static function logGamma($x)
  197. {
  198. // Log Gamma related constants
  199. static $lg_d1 = -0.5772156649015328605195174;
  200. static $lg_d2 = 0.4227843350984671393993777;
  201. static $lg_d4 = 1.791759469228055000094023;
  202. static $lg_p1 = [
  203. 4.945235359296727046734888,
  204. 201.8112620856775083915565,
  205. 2290.838373831346393026739,
  206. 11319.67205903380828685045,
  207. 28557.24635671635335736389,
  208. 38484.96228443793359990269,
  209. 26377.48787624195437963534,
  210. 7225.813979700288197698961,
  211. ];
  212. static $lg_p2 = [
  213. 4.974607845568932035012064,
  214. 542.4138599891070494101986,
  215. 15506.93864978364947665077,
  216. 184793.2904445632425417223,
  217. 1088204.76946882876749847,
  218. 3338152.967987029735917223,
  219. 5106661.678927352456275255,
  220. 3074109.054850539556250927,
  221. ];
  222. static $lg_p4 = [
  223. 14745.02166059939948905062,
  224. 2426813.369486704502836312,
  225. 121475557.4045093227939592,
  226. 2663432449.630976949898078,
  227. 29403789566.34553899906876,
  228. 170266573776.5398868392998,
  229. 492612579337.743088758812,
  230. 560625185622.3951465078242,
  231. ];
  232. static $lg_q1 = [
  233. 67.48212550303777196073036,
  234. 1113.332393857199323513008,
  235. 7738.757056935398733233834,
  236. 27639.87074403340708898585,
  237. 54993.10206226157329794414,
  238. 61611.22180066002127833352,
  239. 36351.27591501940507276287,
  240. 8785.536302431013170870835,
  241. ];
  242. static $lg_q2 = [
  243. 183.0328399370592604055942,
  244. 7765.049321445005871323047,
  245. 133190.3827966074194402448,
  246. 1136705.821321969608938755,
  247. 5267964.117437946917577538,
  248. 13467014.54311101692290052,
  249. 17827365.30353274213975932,
  250. 9533095.591844353613395747,
  251. ];
  252. static $lg_q4 = [
  253. 2690.530175870899333379843,
  254. 639388.5654300092398984238,
  255. 41355999.30241388052042842,
  256. 1120872109.61614794137657,
  257. 14886137286.78813811542398,
  258. 101680358627.2438228077304,
  259. 341747634550.7377132798597,
  260. 446315818741.9713286462081,
  261. ];
  262. static $lg_c = [
  263. -0.001910444077728,
  264. 8.4171387781295e-4,
  265. -5.952379913043012e-4,
  266. 7.93650793500350248e-4,
  267. -0.002777777777777681622553,
  268. 0.08333333333333333331554247,
  269. 0.0057083835261,
  270. ];
  271. // Rough estimate of the fourth root of logGamma_xBig
  272. static $lg_frtbig = 2.25e76;
  273. static $pnt68 = 0.6796875;
  274. if ($x == self::$logGammaCacheX) {
  275. return self::$logGammaCacheResult;
  276. }
  277. $y = $x;
  278. if ($y > 0.0 && $y <= self::LOG_GAMMA_X_MAX_VALUE) {
  279. if ($y <= self::EPS) {
  280. $res = -log($y);
  281. } elseif ($y <= 1.5) {
  282. // ---------------------
  283. // EPS .LT. X .LE. 1.5
  284. // ---------------------
  285. if ($y < $pnt68) {
  286. $corr = -log($y);
  287. $xm1 = $y;
  288. } else {
  289. $corr = 0.0;
  290. $xm1 = $y - 1.0;
  291. }
  292. if ($y <= 0.5 || $y >= $pnt68) {
  293. $xden = 1.0;
  294. $xnum = 0.0;
  295. for ($i = 0; $i < 8; ++$i) {
  296. $xnum = $xnum * $xm1 + $lg_p1[$i];
  297. $xden = $xden * $xm1 + $lg_q1[$i];
  298. }
  299. $res = $corr + $xm1 * ($lg_d1 + $xm1 * ($xnum / $xden));
  300. } else {
  301. $xm2 = $y - 1.0;
  302. $xden = 1.0;
  303. $xnum = 0.0;
  304. for ($i = 0; $i < 8; ++$i) {
  305. $xnum = $xnum * $xm2 + $lg_p2[$i];
  306. $xden = $xden * $xm2 + $lg_q2[$i];
  307. }
  308. $res = $corr + $xm2 * ($lg_d2 + $xm2 * ($xnum / $xden));
  309. }
  310. } elseif ($y <= 4.0) {
  311. // ---------------------
  312. // 1.5 .LT. X .LE. 4.0
  313. // ---------------------
  314. $xm2 = $y - 2.0;
  315. $xden = 1.0;
  316. $xnum = 0.0;
  317. for ($i = 0; $i < 8; ++$i) {
  318. $xnum = $xnum * $xm2 + $lg_p2[$i];
  319. $xden = $xden * $xm2 + $lg_q2[$i];
  320. }
  321. $res = $xm2 * ($lg_d2 + $xm2 * ($xnum / $xden));
  322. } elseif ($y <= 12.0) {
  323. // ----------------------
  324. // 4.0 .LT. X .LE. 12.0
  325. // ----------------------
  326. $xm4 = $y - 4.0;
  327. $xden = -1.0;
  328. $xnum = 0.0;
  329. for ($i = 0; $i < 8; ++$i) {
  330. $xnum = $xnum * $xm4 + $lg_p4[$i];
  331. $xden = $xden * $xm4 + $lg_q4[$i];
  332. }
  333. $res = $lg_d4 + $xm4 * ($xnum / $xden);
  334. } else {
  335. // ---------------------------------
  336. // Evaluate for argument .GE. 12.0
  337. // ---------------------------------
  338. $res = 0.0;
  339. if ($y <= $lg_frtbig) {
  340. $res = $lg_c[6];
  341. $ysq = $y * $y;
  342. for ($i = 0; $i < 6; ++$i) {
  343. $res = $res / $ysq + $lg_c[$i];
  344. }
  345. $res /= $y;
  346. $corr = log($y);
  347. $res = $res + log(self::SQRT2PI) - 0.5 * $corr;
  348. $res += $y * ($corr - 1.0);
  349. }
  350. }
  351. } else {
  352. // --------------------------
  353. // Return for bad arguments
  354. // --------------------------
  355. $res = self::MAX_VALUE;
  356. }
  357. // ------------------------------
  358. // Final adjustments and return
  359. // ------------------------------
  360. self::$logGammaCacheX = $x;
  361. self::$logGammaCacheResult = $res;
  362. return $res;
  363. }
  364. //
  365. // Private implementation of the incomplete Gamma function
  366. //
  367. private static function incompleteGamma($a, $x)
  368. {
  369. static $max = 32;
  370. $summer = 0;
  371. for ($n = 0; $n <= $max; ++$n) {
  372. $divisor = $a;
  373. for ($i = 1; $i <= $n; ++$i) {
  374. $divisor *= ($a + $i);
  375. }
  376. $summer += (pow($x, $n) / $divisor);
  377. }
  378. return pow($x, $a) * exp(0 - $x) * $summer;
  379. }
  380. //
  381. // Private implementation of the Gamma function
  382. //
  383. private static function gamma($data)
  384. {
  385. if ($data == 0.0) {
  386. return 0;
  387. }
  388. static $p0 = 1.000000000190015;
  389. static $p = [
  390. 1 => 76.18009172947146,
  391. 2 => -86.50532032941677,
  392. 3 => 24.01409824083091,
  393. 4 => -1.231739572450155,
  394. 5 => 1.208650973866179e-3,
  395. 6 => -5.395239384953e-6,
  396. ];
  397. $y = $x = $data;
  398. $tmp = $x + 5.5;
  399. $tmp -= ($x + 0.5) * log($tmp);
  400. $summer = $p0;
  401. for ($j = 1; $j <= 6; ++$j) {
  402. $summer += ($p[$j] / ++$y);
  403. }
  404. return exp(0 - $tmp + log(self::SQRT2PI * $summer / $x));
  405. }
  406. /*
  407. * inverse_ncdf.php
  408. * -------------------
  409. * begin : Friday, January 16, 2004
  410. * copyright : (C) 2004 Michael Nickerson
  411. * email : nickersonm@yahoo.com
  412. *
  413. */
  414. private static function inverseNcdf($p)
  415. {
  416. // Inverse ncdf approximation by Peter J. Acklam, implementation adapted to
  417. // PHP by Michael Nickerson, using Dr. Thomas Ziegler's C implementation as
  418. // a guide. http://home.online.no/~pjacklam/notes/invnorm/index.html
  419. // I have not checked the accuracy of this implementation. Be aware that PHP
  420. // will truncate the coeficcients to 14 digits.
  421. // You have permission to use and distribute this function freely for
  422. // whatever purpose you want, but please show common courtesy and give credit
  423. // where credit is due.
  424. // Input paramater is $p - probability - where 0 < p < 1.
  425. // Coefficients in rational approximations
  426. static $a = [
  427. 1 => -3.969683028665376e+01,
  428. 2 => 2.209460984245205e+02,
  429. 3 => -2.759285104469687e+02,
  430. 4 => 1.383577518672690e+02,
  431. 5 => -3.066479806614716e+01,
  432. 6 => 2.506628277459239e+00,
  433. ];
  434. static $b = [
  435. 1 => -5.447609879822406e+01,
  436. 2 => 1.615858368580409e+02,
  437. 3 => -1.556989798598866e+02,
  438. 4 => 6.680131188771972e+01,
  439. 5 => -1.328068155288572e+01,
  440. ];
  441. static $c = [
  442. 1 => -7.784894002430293e-03,
  443. 2 => -3.223964580411365e-01,
  444. 3 => -2.400758277161838e+00,
  445. 4 => -2.549732539343734e+00,
  446. 5 => 4.374664141464968e+00,
  447. 6 => 2.938163982698783e+00,
  448. ];
  449. static $d = [
  450. 1 => 7.784695709041462e-03,
  451. 2 => 3.224671290700398e-01,
  452. 3 => 2.445134137142996e+00,
  453. 4 => 3.754408661907416e+00,
  454. ];
  455. // Define lower and upper region break-points.
  456. $p_low = 0.02425; //Use lower region approx. below this
  457. $p_high = 1 - $p_low; //Use upper region approx. above this
  458. if (0 < $p && $p < $p_low) {
  459. // Rational approximation for lower region.
  460. $q = sqrt(-2 * log($p));
  461. return ((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) /
  462. (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1);
  463. } elseif ($p_low <= $p && $p <= $p_high) {
  464. // Rational approximation for central region.
  465. $q = $p - 0.5;
  466. $r = $q * $q;
  467. return ((((($a[1] * $r + $a[2]) * $r + $a[3]) * $r + $a[4]) * $r + $a[5]) * $r + $a[6]) * $q /
  468. ((((($b[1] * $r + $b[2]) * $r + $b[3]) * $r + $b[4]) * $r + $b[5]) * $r + 1);
  469. } elseif ($p_high < $p && $p < 1) {
  470. // Rational approximation for upper region.
  471. $q = sqrt(-2 * log(1 - $p));
  472. return -((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) /
  473. (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1);
  474. }
  475. // If 0 < p < 1, return a null value
  476. return Functions::NULL();
  477. }
  478. /**
  479. * AVEDEV.
  480. *
  481. * Returns the average of the absolute deviations of data points from their mean.
  482. * AVEDEV is a measure of the variability in a data set.
  483. *
  484. * Excel Function:
  485. * AVEDEV(value1[,value2[, ...]])
  486. *
  487. * @category Statistical Functions
  488. *
  489. * @param mixed ...$args Data values
  490. *
  491. * @return float
  492. */
  493. public static function AVEDEV(...$args)
  494. {
  495. $aArgs = Functions::flattenArrayIndexed($args);
  496. // Return value
  497. $returnValue = null;
  498. $aMean = self::AVERAGE($aArgs);
  499. if ($aMean != Functions::DIV0()) {
  500. $aCount = 0;
  501. foreach ($aArgs as $k => $arg) {
  502. if ((is_bool($arg)) &&
  503. ((!Functions::isCellValue($k)) || (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE))) {
  504. $arg = (int) $arg;
  505. }
  506. // Is it a numeric value?
  507. if ((is_numeric($arg)) && (!is_string($arg))) {
  508. if ($returnValue === null) {
  509. $returnValue = abs($arg - $aMean);
  510. } else {
  511. $returnValue += abs($arg - $aMean);
  512. }
  513. ++$aCount;
  514. }
  515. }
  516. // Return
  517. if ($aCount == 0) {
  518. return Functions::DIV0();
  519. }
  520. return $returnValue / $aCount;
  521. }
  522. return Functions::NAN();
  523. }
  524. /**
  525. * AVERAGE.
  526. *
  527. * Returns the average (arithmetic mean) of the arguments
  528. *
  529. * Excel Function:
  530. * AVERAGE(value1[,value2[, ...]])
  531. *
  532. * @category Statistical Functions
  533. *
  534. * @param mixed ...$args Data values
  535. *
  536. * @return float
  537. */
  538. public static function AVERAGE(...$args)
  539. {
  540. $returnValue = $aCount = 0;
  541. // Loop through arguments
  542. foreach (Functions::flattenArrayIndexed($args) as $k => $arg) {
  543. if ((is_bool($arg)) &&
  544. ((!Functions::isCellValue($k)) || (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE))) {
  545. $arg = (int) $arg;
  546. }
  547. // Is it a numeric value?
  548. if ((is_numeric($arg)) && (!is_string($arg))) {
  549. if ($returnValue === null) {
  550. $returnValue = $arg;
  551. } else {
  552. $returnValue += $arg;
  553. }
  554. ++$aCount;
  555. }
  556. }
  557. // Return
  558. if ($aCount > 0) {
  559. return $returnValue / $aCount;
  560. }
  561. return Functions::DIV0();
  562. }
  563. /**
  564. * AVERAGEA.
  565. *
  566. * Returns the average of its arguments, including numbers, text, and logical values
  567. *
  568. * Excel Function:
  569. * AVERAGEA(value1[,value2[, ...]])
  570. *
  571. * @category Statistical Functions
  572. *
  573. * @param mixed ...$args Data values
  574. *
  575. * @return float
  576. */
  577. public static function AVERAGEA(...$args)
  578. {
  579. $returnValue = null;
  580. $aCount = 0;
  581. // Loop through arguments
  582. foreach (Functions::flattenArrayIndexed($args) as $k => $arg) {
  583. if ((is_bool($arg)) &&
  584. (!Functions::isMatrixValue($k))) {
  585. } else {
  586. if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
  587. if (is_bool($arg)) {
  588. $arg = (int) $arg;
  589. } elseif (is_string($arg)) {
  590. $arg = 0;
  591. }
  592. if ($returnValue === null) {
  593. $returnValue = $arg;
  594. } else {
  595. $returnValue += $arg;
  596. }
  597. ++$aCount;
  598. }
  599. }
  600. }
  601. if ($aCount > 0) {
  602. return $returnValue / $aCount;
  603. }
  604. return Functions::DIV0();
  605. }
  606. /**
  607. * AVERAGEIF.
  608. *
  609. * Returns the average value from a range of cells that contain numbers within the list of arguments
  610. *
  611. * Excel Function:
  612. * AVERAGEIF(value1[,value2[, ...]],condition)
  613. *
  614. * @category Mathematical and Trigonometric Functions
  615. *
  616. * @param mixed $aArgs Data values
  617. * @param string $condition the criteria that defines which cells will be checked
  618. * @param mixed[] $averageArgs Data values
  619. *
  620. * @return float
  621. */
  622. public static function AVERAGEIF($aArgs, $condition, $averageArgs = [])
  623. {
  624. $returnValue = 0;
  625. $aArgs = Functions::flattenArray($aArgs);
  626. $averageArgs = Functions::flattenArray($averageArgs);
  627. if (empty($averageArgs)) {
  628. $averageArgs = $aArgs;
  629. }
  630. $condition = Functions::ifCondition($condition);
  631. // Loop through arguments
  632. $aCount = 0;
  633. foreach ($aArgs as $key => $arg) {
  634. if (!is_numeric($arg)) {
  635. $arg = Calculation::wrapResult(strtoupper($arg));
  636. }
  637. $testCondition = '=' . $arg . $condition;
  638. if (Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
  639. if (($returnValue === null) || ($arg > $returnValue)) {
  640. $returnValue += $arg;
  641. ++$aCount;
  642. }
  643. }
  644. }
  645. if ($aCount > 0) {
  646. return $returnValue / $aCount;
  647. }
  648. return Functions::DIV0();
  649. }
  650. /**
  651. * BETADIST.
  652. *
  653. * Returns the beta distribution.
  654. *
  655. * @param float $value Value at which you want to evaluate the distribution
  656. * @param float $alpha Parameter to the distribution
  657. * @param float $beta Parameter to the distribution
  658. * @param mixed $rMin
  659. * @param mixed $rMax
  660. *
  661. * @return float
  662. */
  663. public static function BETADIST($value, $alpha, $beta, $rMin = 0, $rMax = 1)
  664. {
  665. $value = Functions::flattenSingleValue($value);
  666. $alpha = Functions::flattenSingleValue($alpha);
  667. $beta = Functions::flattenSingleValue($beta);
  668. $rMin = Functions::flattenSingleValue($rMin);
  669. $rMax = Functions::flattenSingleValue($rMax);
  670. if ((is_numeric($value)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) {
  671. if (($value < $rMin) || ($value > $rMax) || ($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax)) {
  672. return Functions::NAN();
  673. }
  674. if ($rMin > $rMax) {
  675. $tmp = $rMin;
  676. $rMin = $rMax;
  677. $rMax = $tmp;
  678. }
  679. $value -= $rMin;
  680. $value /= ($rMax - $rMin);
  681. return self::incompleteBeta($value, $alpha, $beta);
  682. }
  683. return Functions::VALUE();
  684. }
  685. /**
  686. * BETAINV.
  687. *
  688. * Returns the inverse of the beta distribution.
  689. *
  690. * @param float $probability Probability at which you want to evaluate the distribution
  691. * @param float $alpha Parameter to the distribution
  692. * @param float $beta Parameter to the distribution
  693. * @param float $rMin Minimum value
  694. * @param float $rMax Maximum value
  695. *
  696. * @return float
  697. */
  698. public static function BETAINV($probability, $alpha, $beta, $rMin = 0, $rMax = 1)
  699. {
  700. $probability = Functions::flattenSingleValue($probability);
  701. $alpha = Functions::flattenSingleValue($alpha);
  702. $beta = Functions::flattenSingleValue($beta);
  703. $rMin = Functions::flattenSingleValue($rMin);
  704. $rMax = Functions::flattenSingleValue($rMax);
  705. if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) {
  706. if (($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax) || ($probability <= 0) || ($probability > 1)) {
  707. return Functions::NAN();
  708. }
  709. if ($rMin > $rMax) {
  710. $tmp = $rMin;
  711. $rMin = $rMax;
  712. $rMax = $tmp;
  713. }
  714. $a = 0;
  715. $b = 2;
  716. $i = 0;
  717. while ((($b - $a) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) {
  718. $guess = ($a + $b) / 2;
  719. $result = self::BETADIST($guess, $alpha, $beta);
  720. if (($result == $probability) || ($result == 0)) {
  721. $b = $a;
  722. } elseif ($result > $probability) {
  723. $b = $guess;
  724. } else {
  725. $a = $guess;
  726. }
  727. }
  728. if ($i == self::MAX_ITERATIONS) {
  729. return Functions::NA();
  730. }
  731. return round($rMin + $guess * ($rMax - $rMin), 12);
  732. }
  733. return Functions::VALUE();
  734. }
  735. /**
  736. * BINOMDIST.
  737. *
  738. * Returns the individual term binomial distribution probability. Use BINOMDIST in problems with
  739. * a fixed number of tests or trials, when the outcomes of any trial are only success or failure,
  740. * when trials are independent, and when the probability of success is constant throughout the
  741. * experiment. For example, BINOMDIST can calculate the probability that two of the next three
  742. * babies born are male.
  743. *
  744. * @param float $value Number of successes in trials
  745. * @param float $trials Number of trials
  746. * @param float $probability Probability of success on each trial
  747. * @param bool $cumulative
  748. *
  749. * @return float
  750. *
  751. * @todo Cumulative distribution function
  752. */
  753. public static function BINOMDIST($value, $trials, $probability, $cumulative)
  754. {
  755. $value = floor(Functions::flattenSingleValue($value));
  756. $trials = floor(Functions::flattenSingleValue($trials));
  757. $probability = Functions::flattenSingleValue($probability);
  758. if ((is_numeric($value)) && (is_numeric($trials)) && (is_numeric($probability))) {
  759. if (($value < 0) || ($value > $trials)) {
  760. return Functions::NAN();
  761. }
  762. if (($probability < 0) || ($probability > 1)) {
  763. return Functions::NAN();
  764. }
  765. if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
  766. if ($cumulative) {
  767. $summer = 0;
  768. for ($i = 0; $i <= $value; ++$i) {
  769. $summer += MathTrig::COMBIN($trials, $i) * pow($probability, $i) * pow(1 - $probability, $trials - $i);
  770. }
  771. return $summer;
  772. }
  773. return MathTrig::COMBIN($trials, $value) * pow($probability, $value) * pow(1 - $probability, $trials - $value);
  774. }
  775. }
  776. return Functions::VALUE();
  777. }
  778. /**
  779. * CHIDIST.
  780. *
  781. * Returns the one-tailed probability of the chi-squared distribution.
  782. *
  783. * @param float $value Value for the function
  784. * @param float $degrees degrees of freedom
  785. *
  786. * @return float
  787. */
  788. public static function CHIDIST($value, $degrees)
  789. {
  790. $value = Functions::flattenSingleValue($value);
  791. $degrees = floor(Functions::flattenSingleValue($degrees));
  792. if ((is_numeric($value)) && (is_numeric($degrees))) {
  793. if ($degrees < 1) {
  794. return Functions::NAN();
  795. }
  796. if ($value < 0) {
  797. if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) {
  798. return 1;
  799. }
  800. return Functions::NAN();
  801. }
  802. return 1 - (self::incompleteGamma($degrees / 2, $value / 2) / self::gamma($degrees / 2));
  803. }
  804. return Functions::VALUE();
  805. }
  806. /**
  807. * CHIINV.
  808. *
  809. * Returns the one-tailed probability of the chi-squared distribution.
  810. *
  811. * @param float $probability Probability for the function
  812. * @param float $degrees degrees of freedom
  813. *
  814. * @return float
  815. */
  816. public static function CHIINV($probability, $degrees)
  817. {
  818. $probability = Functions::flattenSingleValue($probability);
  819. $degrees = floor(Functions::flattenSingleValue($degrees));
  820. if ((is_numeric($probability)) && (is_numeric($degrees))) {
  821. $xLo = 100;
  822. $xHi = 0;
  823. $x = $xNew = 1;
  824. $dx = 1;
  825. $i = 0;
  826. while ((abs($dx) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) {
  827. // Apply Newton-Raphson step
  828. $result = self::CHIDIST($x, $degrees);
  829. $error = $result - $probability;
  830. if ($error == 0.0) {
  831. $dx = 0;
  832. } elseif ($error < 0.0) {
  833. $xLo = $x;
  834. } else {
  835. $xHi = $x;
  836. }
  837. // Avoid division by zero
  838. if ($result != 0.0) {
  839. $dx = $error / $result;
  840. $xNew = $x - $dx;
  841. }
  842. // If the NR fails to converge (which for example may be the
  843. // case if the initial guess is too rough) we apply a bisection
  844. // step to determine a more narrow interval around the root.
  845. if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) {
  846. $xNew = ($xLo + $xHi) / 2;
  847. $dx = $xNew - $x;
  848. }
  849. $x = $xNew;
  850. }
  851. if ($i == self::MAX_ITERATIONS) {
  852. return Functions::NA();
  853. }
  854. return round($x, 12);
  855. }
  856. return Functions::VALUE();
  857. }
  858. /**
  859. * CONFIDENCE.
  860. *
  861. * Returns the confidence interval for a population mean
  862. *
  863. * @param float $alpha
  864. * @param float $stdDev Standard Deviation
  865. * @param float $size
  866. *
  867. * @return float
  868. */
  869. public static function CONFIDENCE($alpha, $stdDev, $size)
  870. {
  871. $alpha = Functions::flattenSingleValue($alpha);
  872. $stdDev = Functions::flattenSingleValue($stdDev);
  873. $size = floor(Functions::flattenSingleValue($size));
  874. if ((is_numeric($alpha)) && (is_numeric($stdDev)) && (is_numeric($size))) {
  875. if (($alpha <= 0) || ($alpha >= 1)) {
  876. return Functions::NAN();
  877. }
  878. if (($stdDev <= 0) || ($size < 1)) {
  879. return Functions::NAN();
  880. }
  881. return self::NORMSINV(1 - $alpha / 2) * $stdDev / sqrt($size);
  882. }
  883. return Functions::VALUE();
  884. }
  885. /**
  886. * CORREL.
  887. *
  888. * Returns covariance, the average of the products of deviations for each data point pair.
  889. *
  890. * @param mixed $yValues array of mixed Data Series Y
  891. * @param null|mixed $xValues array of mixed Data Series X
  892. *
  893. * @return float
  894. */
  895. public static function CORREL($yValues, $xValues = null)
  896. {
  897. if (($xValues === null) || (!is_array($yValues)) || (!is_array($xValues))) {
  898. return Functions::VALUE();
  899. }
  900. if (!self::checkTrendArrays($yValues, $xValues)) {
  901. return Functions::VALUE();
  902. }
  903. $yValueCount = count($yValues);
  904. $xValueCount = count($xValues);
  905. if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
  906. return Functions::NA();
  907. } elseif ($yValueCount == 1) {
  908. return Functions::DIV0();
  909. }
  910. $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues);
  911. return $bestFitLinear->getCorrelation();
  912. }
  913. /**
  914. * COUNT.
  915. *
  916. * Counts the number of cells that contain numbers within the list of arguments
  917. *
  918. * Excel Function:
  919. * COUNT(value1[,value2[, ...]])
  920. *
  921. * @category Statistical Functions
  922. *
  923. * @param mixed ...$args Data values
  924. *
  925. * @return int
  926. */
  927. public static function COUNT(...$args)
  928. {
  929. $returnValue = 0;
  930. // Loop through arguments
  931. $aArgs = Functions::flattenArrayIndexed($args);
  932. foreach ($aArgs as $k => $arg) {
  933. if ((is_bool($arg)) &&
  934. ((!Functions::isCellValue($k)) || (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE))) {
  935. $arg = (int) $arg;
  936. }
  937. // Is it a numeric value?
  938. if ((is_numeric($arg)) && (!is_string($arg))) {
  939. ++$returnValue;
  940. }
  941. }
  942. return $returnValue;
  943. }
  944. /**
  945. * COUNTA.
  946. *
  947. * Counts the number of cells that are not empty within the list of arguments
  948. *
  949. * Excel Function:
  950. * COUNTA(value1[,value2[, ...]])
  951. *
  952. * @category Statistical Functions
  953. *
  954. * @param mixed ...$args Data values
  955. *
  956. * @return int
  957. */
  958. public static function COUNTA(...$args)
  959. {
  960. $returnValue = 0;
  961. // Loop through arguments
  962. $aArgs = Functions::flattenArray($args);
  963. foreach ($aArgs as $arg) {
  964. // Is it a numeric, boolean or string value?
  965. if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
  966. ++$returnValue;
  967. }
  968. }
  969. return $returnValue;
  970. }
  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. * @category Statistical Functions
  980. *
  981. * @param mixed ...$args Data values
  982. *
  983. * @return int
  984. */
  985. public static function COUNTBLANK(...$args)
  986. {
  987. $returnValue = 0;
  988. // Loop through arguments
  989. $aArgs = Functions::flattenArray($args);
  990. foreach ($aArgs as $arg) {
  991. // Is it a blank cell?
  992. if (($arg === null) || ((is_string($arg)) && ($arg == ''))) {
  993. ++$returnValue;
  994. }
  995. }
  996. return $returnValue;
  997. }
  998. /**
  999. * COUNTIF.
  1000. *
  1001. * Counts the number of cells that contain numbers within the list of arguments
  1002. *
  1003. * Excel Function:
  1004. * COUNTIF(value1[,value2[, ...]],condition)
  1005. *
  1006. * @category Statistical Functions
  1007. *
  1008. * @param mixed $aArgs Data values
  1009. * @param string $condition the criteria that defines which cells will be counted
  1010. *
  1011. * @return int
  1012. */
  1013. public static function COUNTIF($aArgs, $condition)
  1014. {
  1015. $returnValue = 0;
  1016. $aArgs = Functions::flattenArray($aArgs);
  1017. $condition = Functions::ifCondition($condition);
  1018. // Loop through arguments
  1019. foreach ($aArgs as $arg) {
  1020. if (!is_numeric($arg)) {
  1021. $arg = Calculation::wrapResult(strtoupper($arg));
  1022. }
  1023. $testCondition = '=' . $arg . $condition;
  1024. if (Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
  1025. // Is it a value within our criteria
  1026. ++$returnValue;
  1027. }
  1028. }
  1029. return $returnValue;
  1030. }
  1031. /**
  1032. * COVAR.
  1033. *
  1034. * Returns covariance, the average of the products of deviations for each data point pair.
  1035. *
  1036. * @param mixed $yValues array of mixed Data Series Y
  1037. * @param mixed $xValues array of mixed Data Series X
  1038. *
  1039. * @return float
  1040. */
  1041. public static function COVAR($yValues, $xValues)
  1042. {
  1043. if (!self::checkTrendArrays($yValues, $xValues)) {
  1044. return Functions::VALUE();
  1045. }
  1046. $yValueCount = count($yValues);
  1047. $xValueCount = count($xValues);
  1048. if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
  1049. return Functions::NA();
  1050. } elseif ($yValueCount == 1) {
  1051. return Functions::DIV0();
  1052. }
  1053. $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues);
  1054. return $bestFitLinear->getCovariance();
  1055. }
  1056. /**
  1057. * CRITBINOM.
  1058. *
  1059. * Returns the smallest value for which the cumulative binomial distribution is greater
  1060. * than or equal to a criterion value
  1061. *
  1062. * See http://support.microsoft.com/kb/828117/ for details of the algorithm used
  1063. *
  1064. * @param float $trials number of Bernoulli trials
  1065. * @param float $probability probability of a success on each trial
  1066. * @param float $alpha criterion value
  1067. *
  1068. * @return int
  1069. *
  1070. * @todo Warning. This implementation differs from the algorithm detailed on the MS
  1071. * web site in that $CumPGuessMinus1 = $CumPGuess - 1 rather than $CumPGuess - $PGuess
  1072. * This eliminates a potential endless loop error, but may have an adverse affect on the
  1073. * accuracy of the function (although all my tests have so far returned correct results).
  1074. */
  1075. public static function CRITBINOM($trials, $probability, $alpha)
  1076. {
  1077. $trials = floor(Functions::flattenSingleValue($trials));
  1078. $probability = Functions::flattenSingleValue($probability);
  1079. $alpha = Functions::flattenSingleValue($alpha);
  1080. if ((is_numeric($trials)) && (is_numeric($probability)) && (is_numeric($alpha))) {
  1081. if ($trials < 0) {
  1082. return Functions::NAN();
  1083. } elseif (($probability < 0) || ($probability > 1)) {
  1084. return Functions::NAN();
  1085. } elseif (($alpha < 0) || ($alpha > 1)) {
  1086. return Functions::NAN();
  1087. } elseif ($alpha <= 0.5) {
  1088. $t = sqrt(log(1 / ($alpha * $alpha)));
  1089. $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));
  1090. } else {
  1091. $t = sqrt(log(1 / pow(1 - $alpha, 2)));
  1092. $trialsApprox = $t - (2.515517 + 0.802853 * $t + 0.010328 * $t * $t) / (1 + 1.432788 * $t + 0.189269 * $t * $t + 0.001308 * $t * $t * $t);
  1093. }
  1094. $Guess = floor($trials * $probability + $trialsApprox * sqrt($trials * $probability * (1 - $probability)));
  1095. if ($Guess < 0) {
  1096. $Guess = 0;
  1097. } elseif ($Guess > $trials) {
  1098. $Guess = $trials;
  1099. }
  1100. $TotalUnscaledProbability = $UnscaledPGuess = $UnscaledCumPGuess = 0.0;
  1101. $EssentiallyZero = 10e-12;
  1102. $m = floor($trials * $probability);
  1103. ++$TotalUnscaledProbability;
  1104. if ($m == $Guess) {
  1105. ++$UnscaledPGuess;
  1106. }
  1107. if ($m <= $Guess) {
  1108. ++$UnscaledCumPGuess;
  1109. }
  1110. $PreviousValue = 1;
  1111. $Done = false;
  1112. $k = $m + 1;
  1113. while ((!$Done) && ($k <= $trials)) {
  1114. $CurrentValue = $PreviousValue * ($trials - $k + 1) * $probability / ($k * (1 - $probability));
  1115. $TotalUnscaledProbability += $CurrentValue;
  1116. if ($k == $Guess) {
  1117. $UnscaledPGuess += $CurrentValue;
  1118. }
  1119. if ($k <= $Guess) {
  1120. $UnscaledCumPGuess += $CurrentValue;
  1121. }
  1122. if ($CurrentValue <= $EssentiallyZero) {
  1123. $Done = true;
  1124. }
  1125. $PreviousValue = $CurrentValue;
  1126. ++$k;
  1127. }
  1128. $PreviousValue = 1;
  1129. $Done = false;
  1130. $k = $m - 1;
  1131. while ((!$Done) && ($k >= 0)) {
  1132. $CurrentValue = $PreviousValue * $k + 1 * (1 - $probability) / (($trials - $k) * $probability);
  1133. $TotalUnscaledProbability += $CurrentValue;
  1134. if ($k == $Guess) {
  1135. $UnscaledPGuess += $CurrentValue;
  1136. }
  1137. if ($k <= $Guess) {
  1138. $UnscaledCumPGuess += $CurrentValue;
  1139. }
  1140. if ($CurrentValue <= $EssentiallyZero) {
  1141. $Done = true;
  1142. }
  1143. $PreviousValue = $CurrentValue;
  1144. --$k;
  1145. }
  1146. $PGuess = $UnscaledPGuess / $TotalUnscaledProbability;
  1147. $CumPGuess = $UnscaledCumPGuess / $TotalUnscaledProbability;
  1148. $CumPGuessMinus1 = $CumPGuess - 1;
  1149. while (true) {
  1150. if (($CumPGuessMinus1 < $alpha) && ($CumPGuess >= $alpha)) {
  1151. return $Guess;
  1152. } elseif (($CumPGuessMinus1 < $alpha) && ($CumPGuess < $alpha)) {
  1153. $PGuessPlus1 = $PGuess * ($trials - $Guess) * $probability / $Guess / (1 - $probability);
  1154. $CumPGuessMinus1 = $CumPGuess;
  1155. $CumPGuess = $CumPGuess + $PGuessPlus1;
  1156. $PGuess = $PGuessPlus1;
  1157. ++$Guess;
  1158. } elseif (($CumPGuessMinus1 >= $alpha) && ($CumPGuess >= $alpha)) {
  1159. $PGuessMinus1 = $PGuess * $Guess * (1 - $probability) / ($trials - $Guess + 1) / $probability;
  1160. $CumPGuess = $CumPGuessMinus1;
  1161. $CumPGuessMinus1 = $CumPGuessMinus1 - $PGuess;
  1162. $PGuess = $PGuessMinus1;
  1163. --$Guess;
  1164. }
  1165. }
  1166. }
  1167. return Functions::VALUE();
  1168. }
  1169. /**
  1170. * DEVSQ.
  1171. *
  1172. * Returns the sum of squares of deviations of data points from their sample mean.
  1173. *
  1174. * Excel Function:
  1175. * DEVSQ(value1[,value2[, ...]])
  1176. *
  1177. * @category Statistical Functions
  1178. *
  1179. * @param mixed ...$args Data values
  1180. *
  1181. * @return float
  1182. */
  1183. public static function DEVSQ(...$args)
  1184. {
  1185. $aArgs = Functions::flattenArrayIndexed($args);
  1186. // Return value
  1187. $returnValue = null;
  1188. $aMean = self::AVERAGE($aArgs);
  1189. if ($aMean != Functions::DIV0()) {
  1190. $aCount = -1;
  1191. foreach ($aArgs as $k => $arg) {
  1192. // Is it a numeric value?
  1193. if ((is_bool($arg)) &&
  1194. ((!Functions::isCellValue($k)) ||
  1195. (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE))) {
  1196. $arg = (int) $arg;
  1197. }
  1198. if ((is_numeric($arg)) && (!is_string($arg))) {
  1199. if ($returnValue === null) {
  1200. $returnValue = pow(($arg - $aMean), 2);
  1201. } else {
  1202. $returnValue += pow(($arg - $aMean), 2);
  1203. }
  1204. ++$aCount;
  1205. }
  1206. }
  1207. // Return
  1208. if ($returnValue === null) {
  1209. return Functions::NAN();
  1210. }
  1211. return $returnValue;
  1212. }
  1213. return self::NA();
  1214. }
  1215. /**
  1216. * EXPONDIST.
  1217. *
  1218. * Returns the exponential distribution. Use EXPONDIST to model the time between events,
  1219. * such as how long an automated bank teller takes to deliver cash. For example, you can
  1220. * use EXPONDIST to determine the probability that the process takes at most 1 minute.
  1221. *
  1222. * @param float $value Value of the function
  1223. * @param float $lambda The parameter value
  1224. * @param bool $cumulative
  1225. *
  1226. * @return float
  1227. */
  1228. public static function EXPONDIST($value, $lambda, $cumulative)
  1229. {
  1230. $value = Functions::flattenSingleValue($value);
  1231. $lambda = Functions::flattenSingleValue($lambda);
  1232. $cumulative = Functions::flattenSingleValue($cumulative);
  1233. if ((is_numeric($value)) && (is_numeric($lambda))) {
  1234. if (($value < 0) || ($lambda < 0)) {
  1235. return Functions::NAN();
  1236. }
  1237. if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
  1238. if ($cumulative) {
  1239. return 1 - exp(0 - $value * $lambda);
  1240. }
  1241. return $lambda * exp(0 - $value * $lambda);
  1242. }
  1243. }
  1244. return Functions::VALUE();
  1245. }
  1246. /**
  1247. * FISHER.
  1248. *
  1249. * Returns the Fisher transformation at x. This transformation produces a function that
  1250. * is normally distributed rather than skewed. Use this function to perform hypothesis
  1251. * testing on the correlation coefficient.
  1252. *
  1253. * @param float $value
  1254. *
  1255. * @return float
  1256. */
  1257. public static function FISHER($value)
  1258. {
  1259. $value = Functions::flattenSingleValue($value);
  1260. if (is_numeric($value)) {
  1261. if (($value <= -1) || ($value >= 1)) {
  1262. return Functions::NAN();
  1263. }
  1264. return 0.5 * log((1 + $value) / (1 - $value));
  1265. }
  1266. return Functions::VALUE();
  1267. }
  1268. /**
  1269. * FISHERINV.
  1270. *
  1271. * Returns the inverse of the Fisher transformation. Use this transformation when
  1272. * analyzing correlations between ranges or arrays of data. If y = FISHER(x), then
  1273. * FISHERINV(y) = x.
  1274. *
  1275. * @param float $value
  1276. *
  1277. * @return float
  1278. */
  1279. public static function FISHERINV($value)
  1280. {
  1281. $value = Functions::flattenSingleValue($value);
  1282. if (is_numeric($value)) {
  1283. return (exp(2 * $value) - 1) / (exp(2 * $value) + 1);
  1284. }
  1285. return Functions::VALUE();
  1286. }
  1287. /**
  1288. * FORECAST.
  1289. *
  1290. * Calculates, or predicts, a future value by using existing values. The predicted value is a y-value for a given x-value.
  1291. *
  1292. * @param float $xValue Value of X for which we want to find Y
  1293. * @param mixed $yValues array of mixed Data Series Y
  1294. * @param mixed $xValues of mixed Data Series X
  1295. *
  1296. * @return float
  1297. */
  1298. public static function FORECAST($xValue, $yValues, $xValues)
  1299. {
  1300. $xValue = Functions::flattenSingleValue($xValue);
  1301. if (!is_numeric($xValue)) {
  1302. return Functions::VALUE();
  1303. } elseif (!self::checkTrendArrays($yValues, $xValues)) {
  1304. return Functions::VALUE();
  1305. }
  1306. $yValueCount = count($yValues);
  1307. $xValueCount = count($xValues);
  1308. if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
  1309. return Functions::NA();
  1310. } elseif ($yValueCount == 1) {
  1311. return Functions::DIV0();
  1312. }
  1313. $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues);
  1314. return $bestFitLinear->getValueOfYForX($xValue);
  1315. }
  1316. /**
  1317. * GAMMADIST.
  1318. *
  1319. * Returns the gamma distribution.
  1320. *
  1321. * @param float $value Value at which you want to evaluate the distribution
  1322. * @param float $a Parameter to the distribution
  1323. * @param float $b Parameter to the distribution
  1324. * @param bool $cumulative
  1325. *
  1326. * @return float
  1327. */
  1328. public static function GAMMADIST($value, $a, $b, $cumulative)
  1329. {
  1330. $value = Functions::flattenSingleValue($value);
  1331. $a = Functions::flattenSingleValue($a);
  1332. $b = Functions::flattenSingleValue($b);
  1333. if ((is_numeric($value)) && (is_numeric($a)) && (is_numeric($b))) {
  1334. if (($value < 0) || ($a <= 0) || ($b <= 0)) {
  1335. return Functions::NAN();
  1336. }
  1337. if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
  1338. if ($cumulative) {
  1339. return self::incompleteGamma($a, $value / $b) / self::gamma($a);
  1340. }
  1341. return (1 / (pow($b, $a) * self::gamma($a))) * pow($value, $a - 1) * exp(0 - ($value / $b));
  1342. }
  1343. }
  1344. return Functions::VALUE();
  1345. }
  1346. /**
  1347. * GAMMAINV.
  1348. *
  1349. * Returns the inverse of the beta distribution.
  1350. *
  1351. * @param float $probability Probability at which you want to evaluate the distribution
  1352. * @param float $alpha Parameter to the distribution
  1353. * @param float $beta Parameter to the distribution
  1354. *
  1355. * @return float
  1356. */
  1357. public static function GAMMAINV($probability, $alpha, $beta)
  1358. {
  1359. $probability = Functions::flattenSingleValue($probability);
  1360. $alpha = Functions::flattenSingleValue($alpha);
  1361. $beta = Functions::flattenSingleValue($beta);
  1362. if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta))) {
  1363. if (($alpha <= 0) || ($beta <= 0) || ($probability < 0) || ($probability > 1)) {
  1364. return Functions::NAN();
  1365. }
  1366. $xLo = 0;
  1367. $xHi = $alpha * $beta * 5;
  1368. $x = $xNew = 1;
  1369. $error = $pdf = 0;
  1370. $dx = 1024;
  1371. $i = 0;
  1372. while ((abs($dx) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) {
  1373. // Apply Newton-Raphson step
  1374. $error = self::GAMMADIST($x, $alpha, $beta, true) - $probability;
  1375. if ($error < 0.0) {
  1376. $xLo = $x;
  1377. } else {
  1378. $xHi = $x;
  1379. }
  1380. $pdf = self::GAMMADIST($x, $alpha, $beta, false);
  1381. // Avoid division by zero
  1382. if ($pdf != 0.0) {
  1383. $dx = $error / $pdf;
  1384. $xNew = $x - $dx;
  1385. }
  1386. // If the NR fails to converge (which for example may be the
  1387. // case if the initial guess is too rough) we apply a bisection
  1388. // step to determine a more narrow interval around the root.
  1389. if (($xNew < $xLo) || ($xNew > $xHi) || ($pdf == 0.0)) {
  1390. $xNew = ($xLo + $xHi) / 2;
  1391. $dx = $xNew - $x;
  1392. }
  1393. $x = $xNew;
  1394. }
  1395. if ($i == self::MAX_ITERATIONS) {
  1396. return Functions::NA();
  1397. }
  1398. return $x;
  1399. }
  1400. return Functions::VALUE();
  1401. }
  1402. /**
  1403. * GAMMALN.
  1404. *
  1405. * Returns the natural logarithm of the gamma function.
  1406. *
  1407. * @param float $value
  1408. *
  1409. * @return float
  1410. */
  1411. public static function GAMMALN($value)
  1412. {
  1413. $value = Functions::flattenSingleValue($value);
  1414. if (is_numeric($value)) {
  1415. if ($value <= 0) {
  1416. return Functions::NAN();
  1417. }
  1418. return log(self::gamma($value));
  1419. }
  1420. return Functions::VALUE();
  1421. }
  1422. /**
  1423. * GEOMEAN.
  1424. *
  1425. * Returns the geometric mean of an array or range of positive data. For example, you
  1426. * can use GEOMEAN to calculate average growth rate given compound interest with
  1427. * variable rates.
  1428. *
  1429. * Excel Function:
  1430. * GEOMEAN(value1[,value2[, ...]])
  1431. *
  1432. * @category Statistical Functions
  1433. *
  1434. * @param mixed ...$args Data values
  1435. *
  1436. * @return float
  1437. */
  1438. public static function GEOMEAN(...$args)
  1439. {
  1440. $aArgs = Functions::flattenArray($args);
  1441. $aMean = MathTrig::PRODUCT($aArgs);
  1442. if (is_numeric($aMean) && ($aMean > 0)) {
  1443. $aCount = self::COUNT($aArgs);
  1444. if (self::MIN($aArgs) > 0) {
  1445. return pow($aMean, (1 / $aCount));
  1446. }
  1447. }
  1448. return Functions::NAN();
  1449. }
  1450. /**
  1451. * GROWTH.
  1452. *
  1453. * Returns values along a predicted emponential Trend
  1454. *
  1455. * @param array of mixed Data Series Y
  1456. * @param array of mixed Data Series X
  1457. * @param array of mixed Values of X for which we want to find Y
  1458. * @param bool a logical value specifying whether to force the intersect to equal 0
  1459. * @param mixed $yValues
  1460. * @param mixed $xValues
  1461. * @param mixed $newValues
  1462. * @param mixed $const
  1463. *
  1464. * @return array of float
  1465. */
  1466. public static function GROWTH($yValues, $xValues = [], $newValues = [], $const = true)
  1467. {
  1468. $yValues = Functions::flattenArray($yValues);
  1469. $xValues = Functions::flattenArray($xValues);
  1470. $newValues = Functions::flattenArray($newValues);
  1471. $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const);
  1472. $bestFitExponential = Trend::calculate(Trend::TREND_EXPONENTIAL, $yValues, $xValues, $const);
  1473. if (empty($newValues)) {
  1474. $newValues = $bestFitExponential->getXValues();
  1475. }
  1476. $returnArray = [];
  1477. foreach ($newValues as $xValue) {
  1478. $returnArray[0][] = $bestFitExponential->getValueOfYForX($xValue);
  1479. }
  1480. return $returnArray;
  1481. }
  1482. /**
  1483. * HARMEAN.
  1484. *
  1485. * Returns the harmonic mean of a data set. The harmonic mean is the reciprocal of the
  1486. * arithmetic mean of reciprocals.
  1487. *
  1488. * Excel Function:
  1489. * HARMEAN(value1[,value2[, ...]])
  1490. *
  1491. * @category Statistical Functions
  1492. *
  1493. * @param mixed ...$args Data values
  1494. *
  1495. * @return float
  1496. */
  1497. public static function HARMEAN(...$args)
  1498. {
  1499. // Return value
  1500. $returnValue = Functions::NA();
  1501. // Loop through arguments
  1502. $aArgs = Functions::flattenArray($args);
  1503. if (self::MIN($aArgs) < 0) {
  1504. return Functions::NAN();
  1505. }
  1506. $aCount = 0;
  1507. foreach ($aArgs as $arg) {
  1508. // Is it a numeric value?
  1509. if ((is_numeric($arg)) && (!is_string($arg))) {
  1510. if ($arg <= 0) {
  1511. return Functions::NAN();
  1512. }
  1513. if ($returnValue === null) {
  1514. $returnValue = (1 / $arg);
  1515. } else {
  1516. $returnValue += (1 / $arg);
  1517. }
  1518. ++$aCount;
  1519. }
  1520. }
  1521. // Return
  1522. if ($aCount > 0) {
  1523. return 1 / ($returnValue / $aCount);
  1524. }
  1525. return $returnValue;
  1526. }
  1527. /**
  1528. * HYPGEOMDIST.
  1529. *
  1530. * Returns the hypergeometric distribution. HYPGEOMDIST returns the probability of a given number of
  1531. * sample successes, given the sample size, population successes, and population size.
  1532. *
  1533. * @param float $sampleSuccesses Number of successes in the sample
  1534. * @param float $sampleNumber Size of the sample
  1535. * @param float $populationSuccesses Number of successes in the population
  1536. * @param float $populationNumber Population size
  1537. *
  1538. * @return float
  1539. */
  1540. public static function HYPGEOMDIST($sampleSuccesses, $sampleNumber, $populationSuccesses, $populationNumber)
  1541. {
  1542. $sampleSuccesses = floor(Functions::flattenSingleValue($sampleSuccesses));
  1543. $sampleNumber = floor(Functions::flattenSingleValue($sampleNumber));
  1544. $populationSuccesses = floor(Functions::flattenSingleValue($populationSuccesses));
  1545. $populationNumber = floor(Functions::flattenSingleValue($populationNumber));
  1546. if ((is_numeric($sampleSuccesses)) && (is_numeric($sampleNumber)) && (is_numeric($populationSuccesses)) && (is_numeric($populationNumber))) {
  1547. if (($sampleSuccesses < 0) || ($sampleSuccesses > $sampleNumber) || ($sampleSuccesses > $populationSuccesses)) {
  1548. return Functions::NAN();
  1549. }
  1550. if (($sampleNumber <= 0) || ($sampleNumber > $populationNumber)) {
  1551. return Functions::NAN();
  1552. }
  1553. if (($populationSuccesses <= 0) || ($populationSuccesses > $populationNumber)) {
  1554. return Functions::NAN();
  1555. }
  1556. return MathTrig::COMBIN($populationSuccesses, $sampleSuccesses) *
  1557. MathTrig::COMBIN($populationNumber - $populationSuccesses, $sampleNumber - $sampleSuccesses) /
  1558. MathTrig::COMBIN($populationNumber, $sampleNumber);
  1559. }
  1560. return Functions::VALUE();
  1561. }
  1562. /**
  1563. * INTERCEPT.
  1564. *
  1565. * Calculates the point at which a line will intersect the y-axis by using existing x-values and y-values.
  1566. *
  1567. * @param array of mixed Data Series Y
  1568. * @param array of mixed Data Series X
  1569. * @param mixed $yValues
  1570. * @param mixed $xValues
  1571. *
  1572. * @return float
  1573. */
  1574. public static function INTERCEPT($yValues, $xValues)
  1575. {
  1576. if (!self::checkTrendArrays($yValues, $xValues)) {
  1577. return Functions::VALUE();
  1578. }
  1579. $yValueCount = count($yValues);
  1580. $xValueCount = count($xValues);
  1581. if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
  1582. return Functions::NA();
  1583. } elseif ($yValueCount == 1) {
  1584. return Functions::DIV0();
  1585. }
  1586. $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues);
  1587. return $bestFitLinear->getIntersect();
  1588. }
  1589. /**
  1590. * KURT.
  1591. *
  1592. * Returns the kurtosis of a data set. Kurtosis characterizes the relative peakedness
  1593. * or flatness of a distribution compared with the normal distribution. Positive
  1594. * kurtosis indicates a relatively peaked distribution. Negative kurtosis indicates a
  1595. * relatively flat distribution.
  1596. *
  1597. * @param array ...$args Data Series
  1598. *
  1599. * @return float
  1600. */
  1601. public static function KURT(...$args)
  1602. {
  1603. $aArgs = Functions::flattenArrayIndexed($args);
  1604. $mean = self::AVERAGE($aArgs);
  1605. $stdDev = self::STDEV($aArgs);
  1606. if ($stdDev > 0) {
  1607. $count = $summer = 0;
  1608. // Loop through arguments
  1609. foreach ($aArgs as $k => $arg) {
  1610. if ((is_bool($arg)) &&
  1611. (!Functions::isMatrixValue($k))) {
  1612. } else {
  1613. // Is it a numeric value?
  1614. if ((is_numeric($arg)) && (!is_string($arg))) {
  1615. $summer += pow((($arg - $mean) / $stdDev), 4);
  1616. ++$count;
  1617. }
  1618. }
  1619. }
  1620. // Return
  1621. if ($count > 3) {
  1622. return $summer * ($count * ($count + 1) / (($count - 1) * ($count - 2) * ($count - 3))) - (3 * pow($count - 1, 2) / (($count - 2) * ($count - 3)));
  1623. }
  1624. }
  1625. return Functions::DIV0();
  1626. }
  1627. /**
  1628. * LARGE.
  1629. *
  1630. * Returns the nth largest value in a data set. You can use this function to
  1631. * select a value based on its relative standing.
  1632. *
  1633. * Excel Function:
  1634. * LARGE(value1[,value2[, ...]],entry)
  1635. *
  1636. * @category Statistical Functions
  1637. *
  1638. * @param mixed $args Data values
  1639. * @param int $entry Position (ordered from the largest) in the array or range of data to return
  1640. *
  1641. * @return float
  1642. */
  1643. public static function LARGE(...$args)
  1644. {
  1645. $aArgs = Functions::flattenArray($args);
  1646. // Calculate
  1647. $entry = floor(array_pop($aArgs));
  1648. if ((is_numeric($entry)) && (!is_string($entry))) {
  1649. $mArgs = [];
  1650. foreach ($aArgs as $arg) {
  1651. // Is it a numeric value?
  1652. if ((is_numeric($arg)) && (!is_string($arg))) {
  1653. $mArgs[] = $arg;
  1654. }
  1655. }
  1656. $count = self::COUNT($mArgs);
  1657. $entry = floor(--$entry);
  1658. if (($entry < 0) || ($entry >= $count) || ($count == 0)) {
  1659. return Functions::NAN();
  1660. }
  1661. rsort($mArgs);
  1662. return $mArgs[$entry];
  1663. }
  1664. return Functions::VALUE();
  1665. }
  1666. /**
  1667. * LINEST.
  1668. *
  1669. * Calculates the statistics for a line by using the "least squares" method to calculate a straight line that best fits your data,
  1670. * and then returns an array that describes the line.
  1671. *
  1672. * @param array of mixed Data Series Y
  1673. * @param array of mixed Data Series X
  1674. * @param bool a logical value specifying whether to force the intersect to equal 0
  1675. * @param bool a logical value specifying whether to return additional regression statistics
  1676. * @param mixed $yValues
  1677. * @param null|mixed $xValues
  1678. * @param mixed $const
  1679. * @param mixed $stats
  1680. *
  1681. * @return array
  1682. */
  1683. public static function LINEST($yValues, $xValues = null, $const = true, $stats = false)
  1684. {
  1685. $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const);
  1686. $stats = ($stats === null) ? false : (bool) Functions::flattenSingleValue($stats);
  1687. if ($xValues === null) {
  1688. $xValues = range(1, count(Functions::flattenArray($yValues)));
  1689. }
  1690. if (!self::checkTrendArrays($yValues, $xValues)) {
  1691. return Functions::VALUE();
  1692. }
  1693. $yValueCount = count($yValues);
  1694. $xValueCount = count($xValues);
  1695. if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
  1696. return Functions::NA();
  1697. } elseif ($yValueCount == 1) {
  1698. return 0;
  1699. }
  1700. $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues, $const);
  1701. if ($stats) {
  1702. return [
  1703. [
  1704. $bestFitLinear->getSlope(),
  1705. $bestFitLinear->getSlopeSE(),
  1706. $bestFitLinear->getGoodnessOfFit(),
  1707. $bestFitLinear->getF(),
  1708. $bestFitLinear->getSSRegression(),
  1709. ],
  1710. [
  1711. $bestFitLinear->getIntersect(),
  1712. $bestFitLinear->getIntersectSE(),
  1713. $bestFitLinear->getStdevOfResiduals(),
  1714. $bestFitLinear->getDFResiduals(),
  1715. $bestFitLinear->getSSResiduals(),
  1716. ],
  1717. ];
  1718. }
  1719. return [
  1720. $bestFitLinear->getSlope(),
  1721. $bestFitLinear->getIntersect(),
  1722. ];
  1723. }
  1724. /**
  1725. * LOGEST.
  1726. *
  1727. * Calculates an exponential curve that best fits the X and Y data series,
  1728. * and then returns an array that describes the line.
  1729. *
  1730. * @param array of mixed Data Series Y
  1731. * @param array of mixed Data Series X
  1732. * @param bool a logical value specifying whether to force the intersect to equal 0
  1733. * @param bool a logical value specifying whether to return additional regression statistics
  1734. * @param mixed $yValues
  1735. * @param null|mixed $xValues
  1736. * @param mixed $const
  1737. * @param mixed $stats
  1738. *
  1739. * @return array
  1740. */
  1741. public static function LOGEST($yValues, $xValues = null, $const = true, $stats = false)
  1742. {
  1743. $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const);
  1744. $stats = ($stats === null) ? false : (bool) Functions::flattenSingleValue($stats);
  1745. if ($xValues === null) {
  1746. $xValues = range(1, count(Functions::flattenArray($yValues)));
  1747. }
  1748. if (!self::checkTrendArrays($yValues, $xValues)) {
  1749. return Functions::VALUE();
  1750. }
  1751. $yValueCount = count($yValues);
  1752. $xValueCount = count($xValues);
  1753. foreach ($yValues as $value) {
  1754. if ($value <= 0.0) {
  1755. return Functions::NAN();
  1756. }
  1757. }
  1758. if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
  1759. return Functions::NA();
  1760. } elseif ($yValueCount == 1) {
  1761. return 1;
  1762. }
  1763. $bestFitExponential = Trend::calculate(Trend::TREND_EXPONENTIAL, $yValues, $xValues, $const);
  1764. if ($stats) {
  1765. return [
  1766. [
  1767. $bestFitExponential->getSlope(),
  1768. $bestFitExponential->getSlopeSE(),
  1769. $bestFitExponential->getGoodnessOfFit(),
  1770. $bestFitExponential->getF(),
  1771. $bestFitExponential->getSSRegression(),
  1772. ],
  1773. [
  1774. $bestFitExponential->getIntersect(),
  1775. $bestFitExponential->getIntersectSE(),
  1776. $bestFitExponential->getStdevOfResiduals(),
  1777. $bestFitExponential->getDFResiduals(),
  1778. $bestFitExponential->getSSResiduals(),
  1779. ],
  1780. ];
  1781. }
  1782. return [
  1783. $bestFitExponential->getSlope(),
  1784. $bestFitExponential->getIntersect(),
  1785. ];
  1786. }
  1787. /**
  1788. * LOGINV.
  1789. *
  1790. * Returns the inverse of the normal cumulative distribution
  1791. *
  1792. * @param float $probability
  1793. * @param float $mean
  1794. * @param float $stdDev
  1795. *
  1796. * @return float
  1797. *
  1798. * @todo Try implementing P J Acklam's refinement algorithm for greater
  1799. * accuracy if I can get my head round the mathematics
  1800. * (as described at) http://home.online.no/~pjacklam/notes/invnorm/
  1801. */
  1802. public static function LOGINV($probability, $mean, $stdDev)
  1803. {
  1804. $probability = Functions::flattenSingleValue($probability);
  1805. $mean = Functions::flattenSingleValue($mean);
  1806. $stdDev = Functions::flattenSingleValue($stdDev);
  1807. if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
  1808. if (($probability < 0) || ($probability > 1) || ($stdDev <= 0)) {
  1809. return Functions::NAN();
  1810. }
  1811. return exp($mean + $stdDev * self::NORMSINV($probability));
  1812. }
  1813. return Functions::VALUE();
  1814. }
  1815. /**
  1816. * LOGNORMDIST.
  1817. *
  1818. * Returns the cumulative lognormal distribution of x, where ln(x) is normally distributed
  1819. * with parameters mean and standard_dev.
  1820. *
  1821. * @param float $value
  1822. * @param float $mean
  1823. * @param float $stdDev
  1824. *
  1825. * @return float
  1826. */
  1827. public static function LOGNORMDIST($value, $mean, $stdDev)
  1828. {
  1829. $value = Functions::flattenSingleValue($value);
  1830. $mean = Functions::flattenSingleValue($mean);
  1831. $stdDev = Functions::flattenSingleValue($stdDev);
  1832. if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
  1833. if (($value <= 0) || ($stdDev <= 0)) {
  1834. return Functions::NAN();
  1835. }
  1836. return self::NORMSDIST((log($value) - $mean) / $stdDev);
  1837. }
  1838. return Functions::VALUE();
  1839. }
  1840. /**
  1841. * MAX.
  1842. *
  1843. * MAX returns the value of the element of the values passed that has the highest value,
  1844. * with negative numbers considered smaller than positive numbers.
  1845. *
  1846. * Excel Function:
  1847. * MAX(value1[,value2[, ...]])
  1848. *
  1849. * @category Statistical Functions
  1850. *
  1851. * @param mixed ...$args Data values
  1852. *
  1853. * @return float
  1854. */
  1855. public static function MAX(...$args)
  1856. {
  1857. $returnValue = null;
  1858. // Loop through arguments
  1859. $aArgs = Functions::flattenArray($args);
  1860. foreach ($aArgs as $arg) {
  1861. // Is it a numeric value?
  1862. if ((is_numeric($arg)) && (!is_string($arg))) {
  1863. if (($returnValue === null) || ($arg > $returnValue)) {
  1864. $returnValue = $arg;
  1865. }
  1866. }
  1867. }
  1868. if ($returnValue === null) {
  1869. return 0;
  1870. }
  1871. return $returnValue;
  1872. }
  1873. /**
  1874. * MAXA.
  1875. *
  1876. * Returns the greatest value in a list of arguments, including numbers, text, and logical values
  1877. *
  1878. * Excel Function:
  1879. * MAXA(value1[,value2[, ...]])
  1880. *
  1881. * @category Statistical Functions
  1882. *
  1883. * @param mixed ...$args Data values
  1884. *
  1885. * @return float
  1886. */
  1887. public static function MAXA(...$args)
  1888. {
  1889. $returnValue = null;
  1890. // Loop through arguments
  1891. $aArgs = Functions::flattenArray($args);
  1892. foreach ($aArgs as $arg) {
  1893. // Is it a numeric value?
  1894. if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
  1895. if (is_bool($arg)) {
  1896. $arg = (int) $arg;
  1897. } elseif (is_string($arg)) {
  1898. $arg = 0;
  1899. }
  1900. if (($returnValue === null) || ($arg > $returnValue)) {
  1901. $returnValue = $arg;
  1902. }
  1903. }
  1904. }
  1905. if ($returnValue === null) {
  1906. return 0;
  1907. }
  1908. return $returnValue;
  1909. }
  1910. /**
  1911. * MAXIF.
  1912. *
  1913. * Counts the maximum value within a range of cells that contain numbers within the list of arguments
  1914. *
  1915. * Excel Function:
  1916. * MAXIF(value1[,value2[, ...]],condition)
  1917. *
  1918. * @category Mathematical and Trigonometric Functions
  1919. *
  1920. * @param mixed $aArgs Data values
  1921. * @param string $condition the criteria that defines which cells will be checked
  1922. * @param mixed $sumArgs
  1923. *
  1924. * @return float
  1925. */
  1926. public static function MAXIF($aArgs, $condition, $sumArgs = [])
  1927. {
  1928. $returnValue = null;
  1929. $aArgs = Functions::flattenArray($aArgs);
  1930. $sumArgs = Functions::flattenArray($sumArgs);
  1931. if (empty($sumArgs)) {
  1932. $sumArgs = $aArgs;
  1933. }
  1934. $condition = Functions::ifCondition($condition);
  1935. // Loop through arguments
  1936. foreach ($aArgs as $key => $arg) {
  1937. if (!is_numeric($arg)) {
  1938. $arg = Calculation::wrapResult(strtoupper($arg));
  1939. }
  1940. $testCondition = '=' . $arg . $condition;
  1941. if (Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
  1942. if (($returnValue === null) || ($arg > $returnValue)) {
  1943. $returnValue = $arg;
  1944. }
  1945. }
  1946. }
  1947. return $returnValue;
  1948. }
  1949. /**
  1950. * MEDIAN.
  1951. *
  1952. * Returns the median of the given numbers. The median is the number in the middle of a set of numbers.
  1953. *
  1954. * Excel Function:
  1955. * MEDIAN(value1[,value2[, ...]])
  1956. *
  1957. * @category Statistical Functions
  1958. *
  1959. * @param mixed ...$args Data values
  1960. *
  1961. * @return float
  1962. */
  1963. public static function MEDIAN(...$args)
  1964. {
  1965. $returnValue = Functions::NAN();
  1966. $mArgs = [];
  1967. // Loop through arguments
  1968. $aArgs = Functions::flattenArray($args);
  1969. foreach ($aArgs as $arg) {
  1970. // Is it a numeric value?
  1971. if ((is_numeric($arg)) && (!is_string($arg))) {
  1972. $mArgs[] = $arg;
  1973. }
  1974. }
  1975. $mValueCount = count($mArgs);
  1976. if ($mValueCount > 0) {
  1977. sort($mArgs, SORT_NUMERIC);
  1978. $mValueCount = $mValueCount / 2;
  1979. if ($mValueCount == floor($mValueCount)) {
  1980. $returnValue = ($mArgs[$mValueCount--] + $mArgs[$mValueCount]) / 2;
  1981. } else {
  1982. $mValueCount = floor($mValueCount);
  1983. $returnValue = $mArgs[$mValueCount];
  1984. }
  1985. }
  1986. return $returnValue;
  1987. }
  1988. /**
  1989. * MIN.
  1990. *
  1991. * MIN returns the value of the element of the values passed that has the smallest value,
  1992. * with negative numbers considered smaller than positive numbers.
  1993. *
  1994. * Excel Function:
  1995. * MIN(value1[,value2[, ...]])
  1996. *
  1997. * @category Statistical Functions
  1998. *
  1999. * @param mixed ...$args Data values
  2000. *
  2001. * @return float
  2002. */
  2003. public static function MIN(...$args)
  2004. {
  2005. $returnValue = null;
  2006. // Loop through arguments
  2007. $aArgs = Functions::flattenArray($args);
  2008. foreach ($aArgs as $arg) {
  2009. // Is it a numeric value?
  2010. if ((is_numeric($arg)) && (!is_string($arg))) {
  2011. if (($returnValue === null) || ($arg < $returnValue)) {
  2012. $returnValue = $arg;
  2013. }
  2014. }
  2015. }
  2016. if ($returnValue === null) {
  2017. return 0;
  2018. }
  2019. return $returnValue;
  2020. }
  2021. /**
  2022. * MINA.
  2023. *
  2024. * Returns the smallest value in a list of arguments, including numbers, text, and logical values
  2025. *
  2026. * Excel Function:
  2027. * MINA(value1[,value2[, ...]])
  2028. *
  2029. * @category Statistical Functions
  2030. *
  2031. * @param mixed ...$args Data values
  2032. *
  2033. * @return float
  2034. */
  2035. public static function MINA(...$args)
  2036. {
  2037. $returnValue = null;
  2038. // Loop through arguments
  2039. $aArgs = Functions::flattenArray($args);
  2040. foreach ($aArgs as $arg) {
  2041. // Is it a numeric value?
  2042. if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
  2043. if (is_bool($arg)) {
  2044. $arg = (int) $arg;
  2045. } elseif (is_string($arg)) {
  2046. $arg = 0;
  2047. }
  2048. if (($returnValue === null) || ($arg < $returnValue)) {
  2049. $returnValue = $arg;
  2050. }
  2051. }
  2052. }
  2053. if ($returnValue === null) {
  2054. return 0;
  2055. }
  2056. return $returnValue;
  2057. }
  2058. /**
  2059. * MINIF.
  2060. *
  2061. * Returns the minimum value within a range of cells that contain numbers within the list of arguments
  2062. *
  2063. * Excel Function:
  2064. * MINIF(value1[,value2[, ...]],condition)
  2065. *
  2066. * @category Mathematical and Trigonometric Functions
  2067. *
  2068. * @param mixed $aArgs Data values
  2069. * @param string $condition the criteria that defines which cells will be checked
  2070. * @param mixed $sumArgs
  2071. *
  2072. * @return float
  2073. */
  2074. public static function MINIF($aArgs, $condition, $sumArgs = [])
  2075. {
  2076. $returnValue = null;
  2077. $aArgs = Functions::flattenArray($aArgs);
  2078. $sumArgs = Functions::flattenArray($sumArgs);
  2079. if (empty($sumArgs)) {
  2080. $sumArgs = $aArgs;
  2081. }
  2082. $condition = Functions::ifCondition($condition);
  2083. // Loop through arguments
  2084. foreach ($aArgs as $key => $arg) {
  2085. if (!is_numeric($arg)) {
  2086. $arg = Calculation::wrapResult(strtoupper($arg));
  2087. }
  2088. $testCondition = '=' . $arg . $condition;
  2089. if (Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
  2090. if (($returnValue === null) || ($arg < $returnValue)) {
  2091. $returnValue = $arg;
  2092. }
  2093. }
  2094. }
  2095. return $returnValue;
  2096. }
  2097. //
  2098. // Special variant of array_count_values that isn't limited to strings and integers,
  2099. // but can work with floating point numbers as values
  2100. //
  2101. private static function modeCalc($data)
  2102. {
  2103. $frequencyArray = [];
  2104. foreach ($data as $datum) {
  2105. $found = false;
  2106. foreach ($frequencyArray as $key => $value) {
  2107. if ((string) $value['value'] == (string) $datum) {
  2108. ++$frequencyArray[$key]['frequency'];
  2109. $found = true;
  2110. break;
  2111. }
  2112. }
  2113. if (!$found) {
  2114. $frequencyArray[] = [
  2115. 'value' => $datum,
  2116. 'frequency' => 1,
  2117. ];
  2118. }
  2119. }
  2120. foreach ($frequencyArray as $key => $value) {
  2121. $frequencyList[$key] = $value['frequency'];
  2122. $valueList[$key] = $value['value'];
  2123. }
  2124. array_multisort($frequencyList, SORT_DESC, $valueList, SORT_ASC, SORT_NUMERIC, $frequencyArray);
  2125. if ($frequencyArray[0]['frequency'] == 1) {
  2126. return Functions::NA();
  2127. }
  2128. return $frequencyArray[0]['value'];
  2129. }
  2130. /**
  2131. * MODE.
  2132. *
  2133. * Returns the most frequently occurring, or repetitive, value in an array or range of data
  2134. *
  2135. * Excel Function:
  2136. * MODE(value1[,value2[, ...]])
  2137. *
  2138. * @category Statistical Functions
  2139. *
  2140. * @param mixed ...$args Data values
  2141. *
  2142. * @return float
  2143. */
  2144. public static function MODE(...$args)
  2145. {
  2146. $returnValue = Functions::NA();
  2147. // Loop through arguments
  2148. $aArgs = Functions::flattenArray($args);
  2149. $mArgs = [];
  2150. foreach ($aArgs as $arg) {
  2151. // Is it a numeric value?
  2152. if ((is_numeric($arg)) && (!is_string($arg))) {
  2153. $mArgs[] = $arg;
  2154. }
  2155. }
  2156. if (!empty($mArgs)) {
  2157. return self::modeCalc($mArgs);
  2158. }
  2159. return $returnValue;
  2160. }
  2161. /**
  2162. * NEGBINOMDIST.
  2163. *
  2164. * Returns the negative binomial distribution. NEGBINOMDIST returns the probability that
  2165. * there will be number_f failures before the number_s-th success, when the constant
  2166. * probability of a success is probability_s. This function is similar to the binomial
  2167. * distribution, except that the number of successes is fixed, and the number of trials is
  2168. * variable. Like the binomial, trials are assumed to be independent.
  2169. *
  2170. * @param float $failures Number of Failures
  2171. * @param float $successes Threshold number of Successes
  2172. * @param float $probability Probability of success on each trial
  2173. *
  2174. * @return float
  2175. */
  2176. public static function NEGBINOMDIST($failures, $successes, $probability)
  2177. {
  2178. $failures = floor(Functions::flattenSingleValue($failures));
  2179. $successes = floor(Functions::flattenSingleValue($successes));
  2180. $probability = Functions::flattenSingleValue($probability);
  2181. if ((is_numeric($failures)) && (is_numeric($successes)) && (is_numeric($probability))) {
  2182. if (($failures < 0) || ($successes < 1)) {
  2183. return Functions::NAN();
  2184. } elseif (($probability < 0) || ($probability > 1)) {
  2185. return Functions::NAN();
  2186. }
  2187. if (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_GNUMERIC) {
  2188. if (($failures + $successes - 1) <= 0) {
  2189. return Functions::NAN();
  2190. }
  2191. }
  2192. return (MathTrig::COMBIN($failures + $successes - 1, $successes - 1)) * (pow($probability, $successes)) * (pow(1 - $probability, $failures));
  2193. }
  2194. return Functions::VALUE();
  2195. }
  2196. /**
  2197. * NORMDIST.
  2198. *
  2199. * Returns the normal distribution for the specified mean and standard deviation. This
  2200. * function has a very wide range of applications in statistics, including hypothesis
  2201. * testing.
  2202. *
  2203. * @param float $value
  2204. * @param float $mean Mean Value
  2205. * @param float $stdDev Standard Deviation
  2206. * @param bool $cumulative
  2207. *
  2208. * @return float
  2209. */
  2210. public static function NORMDIST($value, $mean, $stdDev, $cumulative)
  2211. {
  2212. $value = Functions::flattenSingleValue($value);
  2213. $mean = Functions::flattenSingleValue($mean);
  2214. $stdDev = Functions::flattenSingleValue($stdDev);
  2215. if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
  2216. if ($stdDev < 0) {
  2217. return Functions::NAN();
  2218. }
  2219. if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
  2220. if ($cumulative) {
  2221. return 0.5 * (1 + Engineering::erfVal(($value - $mean) / ($stdDev * sqrt(2))));
  2222. }
  2223. return (1 / (self::SQRT2PI * $stdDev)) * exp(0 - (pow($value - $mean, 2) / (2 * ($stdDev * $stdDev))));
  2224. }
  2225. }
  2226. return Functions::VALUE();
  2227. }
  2228. /**
  2229. * NORMINV.
  2230. *
  2231. * Returns the inverse of the normal cumulative distribution for the specified mean and standard deviation.
  2232. *
  2233. * @param float $probability
  2234. * @param float $mean Mean Value
  2235. * @param float $stdDev Standard Deviation
  2236. *
  2237. * @return float
  2238. */
  2239. public static function NORMINV($probability, $mean, $stdDev)
  2240. {
  2241. $probability = Functions::flattenSingleValue($probability);
  2242. $mean = Functions::flattenSingleValue($mean);
  2243. $stdDev = Functions::flattenSingleValue($stdDev);
  2244. if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
  2245. if (($probability < 0) || ($probability > 1)) {
  2246. return Functions::NAN();
  2247. }
  2248. if ($stdDev < 0) {
  2249. return Functions::NAN();
  2250. }
  2251. return (self::inverseNcdf($probability) * $stdDev) + $mean;
  2252. }
  2253. return Functions::VALUE();
  2254. }
  2255. /**
  2256. * NORMSDIST.
  2257. *
  2258. * Returns the standard normal cumulative distribution function. The distribution has
  2259. * a mean of 0 (zero) and a standard deviation of one. Use this function in place of a
  2260. * table of standard normal curve areas.
  2261. *
  2262. * @param float $value
  2263. *
  2264. * @return float
  2265. */
  2266. public static function NORMSDIST($value)
  2267. {
  2268. $value = Functions::flattenSingleValue($value);
  2269. return self::NORMDIST($value, 0, 1, true);
  2270. }
  2271. /**
  2272. * NORMSINV.
  2273. *
  2274. * Returns the inverse of the standard normal cumulative distribution
  2275. *
  2276. * @param float $value
  2277. *
  2278. * @return float
  2279. */
  2280. public static function NORMSINV($value)
  2281. {
  2282. return self::NORMINV($value, 0, 1);
  2283. }
  2284. /**
  2285. * PERCENTILE.
  2286. *
  2287. * Returns the nth percentile of values in a range..
  2288. *
  2289. * Excel Function:
  2290. * PERCENTILE(value1[,value2[, ...]],entry)
  2291. *
  2292. * @category Statistical Functions
  2293. *
  2294. * @param mixed $args Data values
  2295. * @param float $entry Percentile value in the range 0..1, inclusive.
  2296. *
  2297. * @return float
  2298. */
  2299. public static function PERCENTILE(...$args)
  2300. {
  2301. $aArgs = Functions::flattenArray($args);
  2302. // Calculate
  2303. $entry = array_pop($aArgs);
  2304. if ((is_numeric($entry)) && (!is_string($entry))) {
  2305. if (($entry < 0) || ($entry > 1)) {
  2306. return Functions::NAN();
  2307. }
  2308. $mArgs = [];
  2309. foreach ($aArgs as $arg) {
  2310. // Is it a numeric value?
  2311. if ((is_numeric($arg)) && (!is_string($arg))) {
  2312. $mArgs[] = $arg;
  2313. }
  2314. }
  2315. $mValueCount = count($mArgs);
  2316. if ($mValueCount > 0) {
  2317. sort($mArgs);
  2318. $count = self::COUNT($mArgs);
  2319. $index = $entry * ($count - 1);
  2320. $iBase = floor($index);
  2321. if ($index == $iBase) {
  2322. return $mArgs[$index];
  2323. }
  2324. $iNext = $iBase + 1;
  2325. $iProportion = $index - $iBase;
  2326. return $mArgs[$iBase] + (($mArgs[$iNext] - $mArgs[$iBase]) * $iProportion);
  2327. }
  2328. }
  2329. return Functions::VALUE();
  2330. }
  2331. /**
  2332. * PERCENTRANK.
  2333. *
  2334. * Returns the rank of a value in a data set as a percentage of the data set.
  2335. *
  2336. * @param array of number An array of, or a reference to, a list of numbers
  2337. * @param number the number whose rank you want to find
  2338. * @param number the number of significant digits for the returned percentage value
  2339. * @param mixed $valueSet
  2340. * @param mixed $value
  2341. * @param mixed $significance
  2342. *
  2343. * @return float
  2344. */
  2345. public static function PERCENTRANK($valueSet, $value, $significance = 3)
  2346. {
  2347. $valueSet = Functions::flattenArray($valueSet);
  2348. $value = Functions::flattenSingleValue($value);
  2349. $significance = ($significance === null) ? 3 : (int) Functions::flattenSingleValue($significance);
  2350. foreach ($valueSet as $key => $valueEntry) {
  2351. if (!is_numeric($valueEntry)) {
  2352. unset($valueSet[$key]);
  2353. }
  2354. }
  2355. sort($valueSet, SORT_NUMERIC);
  2356. $valueCount = count($valueSet);
  2357. if ($valueCount == 0) {
  2358. return Functions::NAN();
  2359. }
  2360. $valueAdjustor = $valueCount - 1;
  2361. if (($value < $valueSet[0]) || ($value > $valueSet[$valueAdjustor])) {
  2362. return Functions::NA();
  2363. }
  2364. $pos = array_search($value, $valueSet);
  2365. if ($pos === false) {
  2366. $pos = 0;
  2367. $testValue = $valueSet[0];
  2368. while ($testValue < $value) {
  2369. $testValue = $valueSet[++$pos];
  2370. }
  2371. --$pos;
  2372. $pos += (($value - $valueSet[$pos]) / ($testValue - $valueSet[$pos]));
  2373. }
  2374. return round($pos / $valueAdjustor, $significance);
  2375. }
  2376. /**
  2377. * PERMUT.
  2378. *
  2379. * Returns the number of permutations for a given number of objects that can be
  2380. * selected from number objects. A permutation is any set or subset of objects or
  2381. * events where internal order is significant. Permutations are different from
  2382. * combinations, for which the internal order is not significant. Use this function
  2383. * for lottery-style probability calculations.
  2384. *
  2385. * @param int $numObjs Number of different objects
  2386. * @param int $numInSet Number of objects in each permutation
  2387. *
  2388. * @return int Number of permutations
  2389. */
  2390. public static function PERMUT($numObjs, $numInSet)
  2391. {
  2392. $numObjs = Functions::flattenSingleValue($numObjs);
  2393. $numInSet = Functions::flattenSingleValue($numInSet);
  2394. if ((is_numeric($numObjs)) && (is_numeric($numInSet))) {
  2395. $numInSet = floor($numInSet);
  2396. if ($numObjs < $numInSet) {
  2397. return Functions::NAN();
  2398. }
  2399. return round(MathTrig::FACT($numObjs) / MathTrig::FACT($numObjs - $numInSet));
  2400. }
  2401. return Functions::VALUE();
  2402. }
  2403. /**
  2404. * POISSON.
  2405. *
  2406. * Returns the Poisson distribution. A common application of the Poisson distribution
  2407. * is predicting the number of events over a specific time, such as the number of
  2408. * cars arriving at a toll plaza in 1 minute.
  2409. *
  2410. * @param float $value
  2411. * @param float $mean Mean Value
  2412. * @param bool $cumulative
  2413. *
  2414. * @return float
  2415. */
  2416. public static function POISSON($value, $mean, $cumulative)
  2417. {
  2418. $value = Functions::flattenSingleValue($value);
  2419. $mean = Functions::flattenSingleValue($mean);
  2420. if ((is_numeric($value)) && (is_numeric($mean))) {
  2421. if (($value < 0) || ($mean <= 0)) {
  2422. return Functions::NAN();
  2423. }
  2424. if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
  2425. if ($cumulative) {
  2426. $summer = 0;
  2427. $floor = floor($value);
  2428. for ($i = 0; $i <= $floor; ++$i) {
  2429. $summer += pow($mean, $i) / MathTrig::FACT($i);
  2430. }
  2431. return exp(0 - $mean) * $summer;
  2432. }
  2433. return (exp(0 - $mean) * pow($mean, $value)) / MathTrig::FACT($value);
  2434. }
  2435. }
  2436. return Functions::VALUE();
  2437. }
  2438. /**
  2439. * QUARTILE.
  2440. *
  2441. * Returns the quartile of a data set.
  2442. *
  2443. * Excel Function:
  2444. * QUARTILE(value1[,value2[, ...]],entry)
  2445. *
  2446. * @category Statistical Functions
  2447. *
  2448. * @param mixed $args Data values
  2449. * @param int $entry Quartile value in the range 1..3, inclusive.
  2450. *
  2451. * @return float
  2452. */
  2453. public static function QUARTILE(...$args)
  2454. {
  2455. $aArgs = Functions::flattenArray($args);
  2456. // Calculate
  2457. $entry = floor(array_pop($aArgs));
  2458. if ((is_numeric($entry)) && (!is_string($entry))) {
  2459. $entry /= 4;
  2460. if (($entry < 0) || ($entry > 1)) {
  2461. return Functions::NAN();
  2462. }
  2463. return self::PERCENTILE($aArgs, $entry);
  2464. }
  2465. return Functions::VALUE();
  2466. }
  2467. /**
  2468. * RANK.
  2469. *
  2470. * Returns the rank of a number in a list of numbers.
  2471. *
  2472. * @param number the number whose rank you want to find
  2473. * @param array of number An array of, or a reference to, a list of numbers
  2474. * @param mixed Order to sort the values in the value set
  2475. * @param mixed $value
  2476. * @param mixed $valueSet
  2477. * @param mixed $order
  2478. *
  2479. * @return float
  2480. */
  2481. public static function RANK($value, $valueSet, $order = 0)
  2482. {
  2483. $value = Functions::flattenSingleValue($value);
  2484. $valueSet = Functions::flattenArray($valueSet);
  2485. $order = ($order === null) ? 0 : (int) Functions::flattenSingleValue($order);
  2486. foreach ($valueSet as $key => $valueEntry) {
  2487. if (!is_numeric($valueEntry)) {
  2488. unset($valueSet[$key]);
  2489. }
  2490. }
  2491. if ($order == 0) {
  2492. rsort($valueSet, SORT_NUMERIC);
  2493. } else {
  2494. sort($valueSet, SORT_NUMERIC);
  2495. }
  2496. $pos = array_search($value, $valueSet);
  2497. if ($pos === false) {
  2498. return Functions::NA();
  2499. }
  2500. return ++$pos;
  2501. }
  2502. /**
  2503. * RSQ.
  2504. *
  2505. * Returns the square of the Pearson product moment correlation coefficient through data points in known_y's and known_x's.
  2506. *
  2507. * @param array of mixed Data Series Y
  2508. * @param array of mixed Data Series X
  2509. * @param mixed $yValues
  2510. * @param mixed $xValues
  2511. *
  2512. * @return float
  2513. */
  2514. public static function RSQ($yValues, $xValues)
  2515. {
  2516. if (!self::checkTrendArrays($yValues, $xValues)) {
  2517. return Functions::VALUE();
  2518. }
  2519. $yValueCount = count($yValues);
  2520. $xValueCount = count($xValues);
  2521. if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
  2522. return Functions::NA();
  2523. } elseif ($yValueCount == 1) {
  2524. return Functions::DIV0();
  2525. }
  2526. $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues);
  2527. return $bestFitLinear->getGoodnessOfFit();
  2528. }
  2529. /**
  2530. * SKEW.
  2531. *
  2532. * Returns the skewness of a distribution. Skewness characterizes the degree of asymmetry
  2533. * of a distribution around its mean. Positive skewness indicates a distribution with an
  2534. * asymmetric tail extending toward more positive values. Negative skewness indicates a
  2535. * distribution with an asymmetric tail extending toward more negative values.
  2536. *
  2537. * @param array ...$args Data Series
  2538. *
  2539. * @return float
  2540. */
  2541. public static function SKEW(...$args)
  2542. {
  2543. $aArgs = Functions::flattenArrayIndexed($args);
  2544. $mean = self::AVERAGE($aArgs);
  2545. $stdDev = self::STDEV($aArgs);
  2546. $count = $summer = 0;
  2547. // Loop through arguments
  2548. foreach ($aArgs as $k => $arg) {
  2549. if ((is_bool($arg)) &&
  2550. (!Functions::isMatrixValue($k))) {
  2551. } else {
  2552. // Is it a numeric value?
  2553. if ((is_numeric($arg)) && (!is_string($arg))) {
  2554. $summer += pow((($arg - $mean) / $stdDev), 3);
  2555. ++$count;
  2556. }
  2557. }
  2558. }
  2559. if ($count > 2) {
  2560. return $summer * ($count / (($count - 1) * ($count - 2)));
  2561. }
  2562. return Functions::DIV0();
  2563. }
  2564. /**
  2565. * SLOPE.
  2566. *
  2567. * Returns the slope of the linear regression line through data points in known_y's and known_x's.
  2568. *
  2569. * @param array of mixed Data Series Y
  2570. * @param array of mixed Data Series X
  2571. * @param mixed $yValues
  2572. * @param mixed $xValues
  2573. *
  2574. * @return float
  2575. */
  2576. public static function SLOPE($yValues, $xValues)
  2577. {
  2578. if (!self::checkTrendArrays($yValues, $xValues)) {
  2579. return Functions::VALUE();
  2580. }
  2581. $yValueCount = count($yValues);
  2582. $xValueCount = count($xValues);
  2583. if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
  2584. return Functions::NA();
  2585. } elseif ($yValueCount == 1) {
  2586. return Functions::DIV0();
  2587. }
  2588. $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues);
  2589. return $bestFitLinear->getSlope();
  2590. }
  2591. /**
  2592. * SMALL.
  2593. *
  2594. * Returns the nth smallest value in a data set. You can use this function to
  2595. * select a value based on its relative standing.
  2596. *
  2597. * Excel Function:
  2598. * SMALL(value1[,value2[, ...]],entry)
  2599. *
  2600. * @category Statistical Functions
  2601. *
  2602. * @param mixed $args Data values
  2603. * @param int $entry Position (ordered from the smallest) in the array or range of data to return
  2604. *
  2605. * @return float
  2606. */
  2607. public static function SMALL(...$args)
  2608. {
  2609. $aArgs = Functions::flattenArray($args);
  2610. // Calculate
  2611. $entry = array_pop($aArgs);
  2612. if ((is_numeric($entry)) && (!is_string($entry))) {
  2613. $mArgs = [];
  2614. foreach ($aArgs as $arg) {
  2615. // Is it a numeric value?
  2616. if ((is_numeric($arg)) && (!is_string($arg))) {
  2617. $mArgs[] = $arg;
  2618. }
  2619. }
  2620. $count = self::COUNT($mArgs);
  2621. $entry = floor(--$entry);
  2622. if (($entry < 0) || ($entry >= $count) || ($count == 0)) {
  2623. return Functions::NAN();
  2624. }
  2625. sort($mArgs);
  2626. return $mArgs[$entry];
  2627. }
  2628. return Functions::VALUE();
  2629. }
  2630. /**
  2631. * STANDARDIZE.
  2632. *
  2633. * Returns a normalized value from a distribution characterized by mean and standard_dev.
  2634. *
  2635. * @param float $value Value to normalize
  2636. * @param float $mean Mean Value
  2637. * @param float $stdDev Standard Deviation
  2638. *
  2639. * @return float Standardized value
  2640. */
  2641. public static function STANDARDIZE($value, $mean, $stdDev)
  2642. {
  2643. $value = Functions::flattenSingleValue($value);
  2644. $mean = Functions::flattenSingleValue($mean);
  2645. $stdDev = Functions::flattenSingleValue($stdDev);
  2646. if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
  2647. if ($stdDev <= 0) {
  2648. return Functions::NAN();
  2649. }
  2650. return ($value - $mean) / $stdDev;
  2651. }
  2652. return Functions::VALUE();
  2653. }
  2654. /**
  2655. * STDEV.
  2656. *
  2657. * Estimates standard deviation based on a sample. The standard deviation is a measure of how
  2658. * widely values are dispersed from the average value (the mean).
  2659. *
  2660. * Excel Function:
  2661. * STDEV(value1[,value2[, ...]])
  2662. *
  2663. * @category Statistical Functions
  2664. *
  2665. * @param mixed ...$args Data values
  2666. *
  2667. * @return float
  2668. */
  2669. public static function STDEV(...$args)
  2670. {
  2671. $aArgs = Functions::flattenArrayIndexed($args);
  2672. // Return value
  2673. $returnValue = null;
  2674. $aMean = self::AVERAGE($aArgs);
  2675. if ($aMean !== null) {
  2676. $aCount = -1;
  2677. foreach ($aArgs as $k => $arg) {
  2678. if ((is_bool($arg)) &&
  2679. ((!Functions::isCellValue($k)) || (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE))) {
  2680. $arg = (int) $arg;
  2681. }
  2682. // Is it a numeric value?
  2683. if ((is_numeric($arg)) && (!is_string($arg))) {
  2684. if ($returnValue === null) {
  2685. $returnValue = pow(($arg - $aMean), 2);
  2686. } else {
  2687. $returnValue += pow(($arg - $aMean), 2);
  2688. }
  2689. ++$aCount;
  2690. }
  2691. }
  2692. // Return
  2693. if (($aCount > 0) && ($returnValue >= 0)) {
  2694. return sqrt($returnValue / $aCount);
  2695. }
  2696. }
  2697. return Functions::DIV0();
  2698. }
  2699. /**
  2700. * STDEVA.
  2701. *
  2702. * Estimates standard deviation based on a sample, including numbers, text, and logical values
  2703. *
  2704. * Excel Function:
  2705. * STDEVA(value1[,value2[, ...]])
  2706. *
  2707. * @category Statistical Functions
  2708. *
  2709. * @param mixed ...$args Data values
  2710. *
  2711. * @return float
  2712. */
  2713. public static function STDEVA(...$args)
  2714. {
  2715. $aArgs = Functions::flattenArrayIndexed($args);
  2716. $returnValue = null;
  2717. $aMean = self::AVERAGEA($aArgs);
  2718. if ($aMean !== null) {
  2719. $aCount = -1;
  2720. foreach ($aArgs as $k => $arg) {
  2721. if ((is_bool($arg)) &&
  2722. (!Functions::isMatrixValue($k))) {
  2723. } else {
  2724. // Is it a numeric value?
  2725. if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) {
  2726. if (is_bool($arg)) {
  2727. $arg = (int) $arg;
  2728. } elseif (is_string($arg)) {
  2729. $arg = 0;
  2730. }
  2731. if ($returnValue === null) {
  2732. $returnValue = pow(($arg - $aMean), 2);
  2733. } else {
  2734. $returnValue += pow(($arg - $aMean), 2);
  2735. }
  2736. ++$aCount;
  2737. }
  2738. }
  2739. }
  2740. if (($aCount > 0) && ($returnValue >= 0)) {
  2741. return sqrt($returnValue / $aCount);
  2742. }
  2743. }
  2744. return Functions::DIV0();
  2745. }
  2746. /**
  2747. * STDEVP.
  2748. *
  2749. * Calculates standard deviation based on the entire population
  2750. *
  2751. * Excel Function:
  2752. * STDEVP(value1[,value2[, ...]])
  2753. *
  2754. * @category Statistical Functions
  2755. *
  2756. * @param mixed ...$args Data values
  2757. *
  2758. * @return float
  2759. */
  2760. public static function STDEVP(...$args)
  2761. {
  2762. $aArgs = Functions::flattenArrayIndexed($args);
  2763. $returnValue = null;
  2764. $aMean = self::AVERAGE($aArgs);
  2765. if ($aMean !== null) {
  2766. $aCount = 0;
  2767. foreach ($aArgs as $k => $arg) {
  2768. if ((is_bool($arg)) &&
  2769. ((!Functions::isCellValue($k)) || (Functions::getCompatibilityMode() == Functions::COMPATIBILITY_OPENOFFICE))) {
  2770. $arg = (int) $arg;
  2771. }
  2772. // Is it a numeric value?
  2773. if ((is_numeric($arg)) && (!is_string($arg))) {
  2774. if ($returnValue === null) {
  2775. $returnValue = pow(($arg - $aMean), 2);
  2776. } else {
  2777. $returnValue += pow(($arg - $aMean), 2);
  2778. }
  2779. ++$aCount;
  2780. }
  2781. }
  2782. if (($aCount > 0) && ($returnValue >= 0)) {
  2783. return sqrt($returnValue / $aCount);
  2784. }
  2785. }
  2786. return Functions::DIV0();
  2787. }
  2788. /**
  2789. * STDEVPA.
  2790. *
  2791. * Calculates standard deviation based on the entire population, including numbers, text, and logical values
  2792. *
  2793. * Excel Function:
  2794. * STDEVPA(value1[,value2[, ...]])
  2795. *
  2796. * @category Statistical Functions
  2797. *
  2798. * @param mixed ...$args Data values
  2799. *
  2800. * @return float
  2801. */
  2802. public static function STDEVPA(...$args)
  2803. {
  2804. $aArgs = Functions::flattenArrayIndexed($args);
  2805. $returnValue = null;
  2806. $aMean = self::AVERAGEA($aArgs);
  2807. if ($aMean !== null) {
  2808. $aCount = 0;
  2809. foreach ($aArgs as $k => $arg) {
  2810. if ((is_bool($arg)) &&
  2811. (!Functions::isMatrixValue($k))) {
  2812. } else {
  2813. // Is it a numeric value?
  2814. if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) {
  2815. if (is_bool($arg)) {
  2816. $arg = (int) $arg;
  2817. } elseif (is_string($arg)) {
  2818. $arg = 0;
  2819. }
  2820. if ($returnValue === null) {
  2821. $returnValue = pow(($arg - $aMean), 2);
  2822. } else {
  2823. $returnValue += pow(($arg - $aMean), 2);
  2824. }
  2825. ++$aCount;
  2826. }
  2827. }
  2828. }
  2829. if (($aCount > 0) && ($returnValue >= 0)) {
  2830. return sqrt($returnValue / $aCount);
  2831. }
  2832. }
  2833. return Functions::DIV0();
  2834. }
  2835. /**
  2836. * STEYX.
  2837. *
  2838. * Returns the standard error of the predicted y-value for each x in the regression.
  2839. *
  2840. * @param array of mixed Data Series Y
  2841. * @param array of mixed Data Series X
  2842. * @param mixed $yValues
  2843. * @param mixed $xValues
  2844. *
  2845. * @return float
  2846. */
  2847. public static function STEYX($yValues, $xValues)
  2848. {
  2849. if (!self::checkTrendArrays($yValues, $xValues)) {
  2850. return Functions::VALUE();
  2851. }
  2852. $yValueCount = count($yValues);
  2853. $xValueCount = count($xValues);
  2854. if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
  2855. return Functions::NA();
  2856. } elseif ($yValueCount == 1) {
  2857. return Functions::DIV0();
  2858. }
  2859. $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues);
  2860. return $bestFitLinear->getStdevOfResiduals();
  2861. }
  2862. /**
  2863. * TDIST.
  2864. *
  2865. * Returns the probability of Student's T distribution.
  2866. *
  2867. * @param float $value Value for the function
  2868. * @param float $degrees degrees of freedom
  2869. * @param float $tails number of tails (1 or 2)
  2870. *
  2871. * @return float
  2872. */
  2873. public static function TDIST($value, $degrees, $tails)
  2874. {
  2875. $value = Functions::flattenSingleValue($value);
  2876. $degrees = floor(Functions::flattenSingleValue($degrees));
  2877. $tails = floor(Functions::flattenSingleValue($tails));
  2878. if ((is_numeric($value)) && (is_numeric($degrees)) && (is_numeric($tails))) {
  2879. if (($value < 0) || ($degrees < 1) || ($tails < 1) || ($tails > 2)) {
  2880. return Functions::NAN();
  2881. }
  2882. // tdist, which finds the probability that corresponds to a given value
  2883. // of t with k degrees of freedom. This algorithm is translated from a
  2884. // pascal function on p81 of "Statistical Computing in Pascal" by D
  2885. // Cooke, A H Craven & G M Clark (1985: Edward Arnold (Pubs.) Ltd:
  2886. // London). The above Pascal algorithm is itself a translation of the
  2887. // fortran algoritm "AS 3" by B E Cooper of the Atlas Computer
  2888. // Laboratory as reported in (among other places) "Applied Statistics
  2889. // Algorithms", editied by P Griffiths and I D Hill (1985; Ellis
  2890. // Horwood Ltd.; W. Sussex, England).
  2891. $tterm = $degrees;
  2892. $ttheta = atan2($value, sqrt($tterm));
  2893. $tc = cos($ttheta);
  2894. $ts = sin($ttheta);
  2895. $tsum = 0;
  2896. if (($degrees % 2) == 1) {
  2897. $ti = 3;
  2898. $tterm = $tc;
  2899. } else {
  2900. $ti = 2;
  2901. $tterm = 1;
  2902. }
  2903. $tsum = $tterm;
  2904. while ($ti < $degrees) {
  2905. $tterm *= $tc * $tc * ($ti - 1) / $ti;
  2906. $tsum += $tterm;
  2907. $ti += 2;
  2908. }
  2909. $tsum *= $ts;
  2910. if (($degrees % 2) == 1) {
  2911. $tsum = Functions::M_2DIVPI * ($tsum + $ttheta);
  2912. }
  2913. $tValue = 0.5 * (1 + $tsum);
  2914. if ($tails == 1) {
  2915. return 1 - abs($tValue);
  2916. }
  2917. return 1 - abs((1 - $tValue) - $tValue);
  2918. }
  2919. return Functions::VALUE();
  2920. }
  2921. /**
  2922. * TINV.
  2923. *
  2924. * Returns the one-tailed probability of the chi-squared distribution.
  2925. *
  2926. * @param float $probability Probability for the function
  2927. * @param float $degrees degrees of freedom
  2928. *
  2929. * @return float
  2930. */
  2931. public static function TINV($probability, $degrees)
  2932. {
  2933. $probability = Functions::flattenSingleValue($probability);
  2934. $degrees = floor(Functions::flattenSingleValue($degrees));
  2935. if ((is_numeric($probability)) && (is_numeric($degrees))) {
  2936. $xLo = 100;
  2937. $xHi = 0;
  2938. $x = $xNew = 1;
  2939. $dx = 1;
  2940. $i = 0;
  2941. while ((abs($dx) > Functions::PRECISION) && ($i++ < self::MAX_ITERATIONS)) {
  2942. // Apply Newton-Raphson step
  2943. $result = self::TDIST($x, $degrees, 2);
  2944. $error = $result - $probability;
  2945. if ($error == 0.0) {
  2946. $dx = 0;
  2947. } elseif ($error < 0.0) {
  2948. $xLo = $x;
  2949. } else {
  2950. $xHi = $x;
  2951. }
  2952. // Avoid division by zero
  2953. if ($result != 0.0) {
  2954. $dx = $error / $result;
  2955. $xNew = $x - $dx;
  2956. }
  2957. // If the NR fails to converge (which for example may be the
  2958. // case if the initial guess is too rough) we apply a bisection
  2959. // step to determine a more narrow interval around the root.
  2960. if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) {
  2961. $xNew = ($xLo + $xHi) / 2;
  2962. $dx = $xNew - $x;
  2963. }
  2964. $x = $xNew;
  2965. }
  2966. if ($i == self::MAX_ITERATIONS) {
  2967. return Functions::NA();
  2968. }
  2969. return round($x, 12);
  2970. }
  2971. return Functions::VALUE();
  2972. }
  2973. /**
  2974. * TREND.
  2975. *
  2976. * Returns values along a linear Trend
  2977. *
  2978. * @param array of mixed Data Series Y
  2979. * @param array of mixed Data Series X
  2980. * @param array of mixed Values of X for which we want to find Y
  2981. * @param bool a logical value specifying whether to force the intersect to equal 0
  2982. * @param mixed $yValues
  2983. * @param mixed $xValues
  2984. * @param mixed $newValues
  2985. * @param mixed $const
  2986. *
  2987. * @return array of float
  2988. */
  2989. public static function TREND($yValues, $xValues = [], $newValues = [], $const = true)
  2990. {
  2991. $yValues = Functions::flattenArray($yValues);
  2992. $xValues = Functions::flattenArray($xValues);
  2993. $newValues = Functions::flattenArray($newValues);
  2994. $const = ($const === null) ? true : (bool) Functions::flattenSingleValue($const);
  2995. $bestFitLinear = Trend::calculate(Trend::TREND_LINEAR, $yValues, $xValues, $const);
  2996. if (empty($newValues)) {
  2997. $newValues = $bestFitLinear->getXValues();
  2998. }
  2999. $returnArray = [];
  3000. foreach ($newValues as $xValue) {
  3001. $returnArray[0][] = $bestFitLinear->getValueOfYForX($xValue);
  3002. }
  3003. return $returnArray;
  3004. }
  3005. /**
  3006. * TRIMMEAN.
  3007. *
  3008. * Returns the mean of the interior of a data set. TRIMMEAN calculates the mean
  3009. * taken by excluding a percentage of data points from the top and bottom tails
  3010. * of a data set.
  3011. *
  3012. * Excel Function:
  3013. * TRIMEAN(value1[,value2[, ...]], $discard)
  3014. *
  3015. * @category Statistical Functions
  3016. *
  3017. * @param mixed $args Data values
  3018. * @param float $discard Percentage to discard
  3019. *
  3020. * @return float
  3021. */
  3022. public static function TRIMMEAN(...$args)
  3023. {
  3024. $aArgs = Functions::flattenArray($args);
  3025. // Calculate
  3026. $percent = array_pop($aArgs);
  3027. if ((is_numeric($percent)) && (!is_string($percent))) {
  3028. if (($percent < 0) || ($percent > 1)) {
  3029. return Functions::NAN();
  3030. }
  3031. $mArgs = [];
  3032. foreach ($aArgs as $arg) {
  3033. // Is it a numeric value?
  3034. if ((is_numeric($arg)) && (!is_string($arg))) {
  3035. $mArgs[] = $arg;
  3036. }
  3037. }
  3038. $discard = floor(self::COUNT($mArgs) * $percent / 2);
  3039. sort($mArgs);
  3040. for ($i = 0; $i < $discard; ++$i) {
  3041. array_pop($mArgs);
  3042. array_shift($mArgs);
  3043. }
  3044. return self::AVERAGE($mArgs);
  3045. }
  3046. return Functions::VALUE();
  3047. }
  3048. /**
  3049. * VARFunc.
  3050. *
  3051. * Estimates variance based on a sample.
  3052. *
  3053. * Excel Function:
  3054. * VAR(value1[,value2[, ...]])
  3055. *
  3056. * @category Statistical Functions
  3057. *
  3058. * @param mixed ...$args Data values
  3059. *
  3060. * @return float
  3061. */
  3062. public static function VARFunc(...$args)
  3063. {
  3064. $returnValue = Functions::DIV0();
  3065. $summerA = $summerB = 0;
  3066. // Loop through arguments
  3067. $aArgs = Functions::flattenArray($args);
  3068. $aCount = 0;
  3069. foreach ($aArgs as $arg) {
  3070. if (is_bool($arg)) {
  3071. $arg = (int) $arg;
  3072. }
  3073. // Is it a numeric value?
  3074. if ((is_numeric($arg)) && (!is_string($arg))) {
  3075. $summerA += ($arg * $arg);
  3076. $summerB += $arg;
  3077. ++$aCount;
  3078. }
  3079. }
  3080. if ($aCount > 1) {
  3081. $summerA *= $aCount;
  3082. $summerB *= $summerB;
  3083. $returnValue = ($summerA - $summerB) / ($aCount * ($aCount - 1));
  3084. }
  3085. return $returnValue;
  3086. }
  3087. /**
  3088. * VARA.
  3089. *
  3090. * Estimates variance based on a sample, including numbers, text, and logical values
  3091. *
  3092. * Excel Function:
  3093. * VARA(value1[,value2[, ...]])
  3094. *
  3095. * @category Statistical Functions
  3096. *
  3097. * @param mixed ...$args Data values
  3098. *
  3099. * @return float
  3100. */
  3101. public static function VARA(...$args)
  3102. {
  3103. $returnValue = Functions::DIV0();
  3104. $summerA = $summerB = 0;
  3105. // Loop through arguments
  3106. $aArgs = Functions::flattenArrayIndexed($args);
  3107. $aCount = 0;
  3108. foreach ($aArgs as $k => $arg) {
  3109. if ((is_string($arg)) &&
  3110. (Functions::isValue($k))) {
  3111. return Functions::VALUE();
  3112. } elseif ((is_string($arg)) &&
  3113. (!Functions::isMatrixValue($k))) {
  3114. } else {
  3115. // Is it a numeric value?
  3116. if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) {
  3117. if (is_bool($arg)) {
  3118. $arg = (int) $arg;
  3119. } elseif (is_string($arg)) {
  3120. $arg = 0;
  3121. }
  3122. $summerA += ($arg * $arg);
  3123. $summerB += $arg;
  3124. ++$aCount;
  3125. }
  3126. }
  3127. }
  3128. if ($aCount > 1) {
  3129. $summerA *= $aCount;
  3130. $summerB *= $summerB;
  3131. $returnValue = ($summerA - $summerB) / ($aCount * ($aCount - 1));
  3132. }
  3133. return $returnValue;
  3134. }
  3135. /**
  3136. * VARP.
  3137. *
  3138. * Calculates variance based on the entire population
  3139. *
  3140. * Excel Function:
  3141. * VARP(value1[,value2[, ...]])
  3142. *
  3143. * @category Statistical Functions
  3144. *
  3145. * @param mixed ...$args Data values
  3146. *
  3147. * @return float
  3148. */
  3149. public static function VARP(...$args)
  3150. {
  3151. // Return value
  3152. $returnValue = Functions::DIV0();
  3153. $summerA = $summerB = 0;
  3154. // Loop through arguments
  3155. $aArgs = Functions::flattenArray($args);
  3156. $aCount = 0;
  3157. foreach ($aArgs as $arg) {
  3158. if (is_bool($arg)) {
  3159. $arg = (int) $arg;
  3160. }
  3161. // Is it a numeric value?
  3162. if ((is_numeric($arg)) && (!is_string($arg))) {
  3163. $summerA += ($arg * $arg);
  3164. $summerB += $arg;
  3165. ++$aCount;
  3166. }
  3167. }
  3168. if ($aCount > 0) {
  3169. $summerA *= $aCount;
  3170. $summerB *= $summerB;
  3171. $returnValue = ($summerA - $summerB) / ($aCount * $aCount);
  3172. }
  3173. return $returnValue;
  3174. }
  3175. /**
  3176. * VARPA.
  3177. *
  3178. * Calculates variance based on the entire population, including numbers, text, and logical values
  3179. *
  3180. * Excel Function:
  3181. * VARPA(value1[,value2[, ...]])
  3182. *
  3183. * @category Statistical Functions
  3184. *
  3185. * @param mixed ...$args Data values
  3186. *
  3187. * @return float
  3188. */
  3189. public static function VARPA(...$args)
  3190. {
  3191. $returnValue = Functions::DIV0();
  3192. $summerA = $summerB = 0;
  3193. // Loop through arguments
  3194. $aArgs = Functions::flattenArrayIndexed($args);
  3195. $aCount = 0;
  3196. foreach ($aArgs as $k => $arg) {
  3197. if ((is_string($arg)) &&
  3198. (Functions::isValue($k))) {
  3199. return Functions::VALUE();
  3200. } elseif ((is_string($arg)) &&
  3201. (!Functions::isMatrixValue($k))) {
  3202. } else {
  3203. // Is it a numeric value?
  3204. if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) {
  3205. if (is_bool($arg)) {
  3206. $arg = (int) $arg;
  3207. } elseif (is_string($arg)) {
  3208. $arg = 0;
  3209. }
  3210. $summerA += ($arg * $arg);
  3211. $summerB += $arg;
  3212. ++$aCount;
  3213. }
  3214. }
  3215. }
  3216. if ($aCount > 0) {
  3217. $summerA *= $aCount;
  3218. $summerB *= $summerB;
  3219. $returnValue = ($summerA - $summerB) / ($aCount * $aCount);
  3220. }
  3221. return $returnValue;
  3222. }
  3223. /**
  3224. * WEIBULL.
  3225. *
  3226. * Returns the Weibull distribution. Use this distribution in reliability
  3227. * analysis, such as calculating a device's mean time to failure.
  3228. *
  3229. * @param float $value
  3230. * @param float $alpha Alpha Parameter
  3231. * @param float $beta Beta Parameter
  3232. * @param bool $cumulative
  3233. *
  3234. * @return float
  3235. */
  3236. public static function WEIBULL($value, $alpha, $beta, $cumulative)
  3237. {
  3238. $value = Functions::flattenSingleValue($value);
  3239. $alpha = Functions::flattenSingleValue($alpha);
  3240. $beta = Functions::flattenSingleValue($beta);
  3241. if ((is_numeric($value)) && (is_numeric($alpha)) && (is_numeric($beta))) {
  3242. if (($value < 0) || ($alpha <= 0) || ($beta <= 0)) {
  3243. return Functions::NAN();
  3244. }
  3245. if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
  3246. if ($cumulative) {
  3247. return 1 - exp(0 - pow($value / $beta, $alpha));
  3248. }
  3249. return ($alpha / pow($beta, $alpha)) * pow($value, $alpha - 1) * exp(0 - pow($value / $beta, $alpha));
  3250. }
  3251. }
  3252. return Functions::VALUE();
  3253. }
  3254. /**
  3255. * ZTEST.
  3256. *
  3257. * Returns the Weibull distribution. Use this distribution in reliability
  3258. * analysis, such as calculating a device's mean time to failure.
  3259. *
  3260. * @param float $dataSet
  3261. * @param float $m0 Alpha Parameter
  3262. * @param float $sigma Beta Parameter
  3263. *
  3264. * @return float
  3265. */
  3266. public static function ZTEST($dataSet, $m0, $sigma = null)
  3267. {
  3268. $dataSet = Functions::flattenArrayIndexed($dataSet);
  3269. $m0 = Functions::flattenSingleValue($m0);
  3270. $sigma = Functions::flattenSingleValue($sigma);
  3271. if ($sigma === null) {
  3272. $sigma = self::STDEV($dataSet);
  3273. }
  3274. $n = count($dataSet);
  3275. return 1 - self::NORMSDIST((self::AVERAGE($dataSet) - $m0) / ($sigma / sqrt($n)));
  3276. }
  3277. }