StatisticalAnalysis.cs 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. //
  5. // Purpose: This class is used for Statistical Analysis
  6. //
  7. using System;
  8. using System.Collections;
  9. namespace FastReport.DataVisualization.Charting.Formulas
  10. {
  11. /// <summary>
  12. ///
  13. /// </summary>
  14. internal class StatisticalAnalysis : IFormula
  15. {
  16. #region Error strings
  17. // Error strings
  18. //internal string inputArrayStart = "Formula requires";
  19. //internal string inputArrayEnd = "arrays";
  20. #endregion
  21. #region Parameters
  22. /// <summary>
  23. /// Formula Module name
  24. /// </summary>
  25. virtual public string Name { get { return SR.FormulaNameStatisticalAnalysis; } }
  26. #endregion // Parameters
  27. #region Methods
  28. /// <summary>
  29. /// Default constructor
  30. /// </summary>
  31. public StatisticalAnalysis()
  32. {
  33. }
  34. /// <summary>
  35. /// The first method in the module, which converts a formula
  36. /// name to the corresponding private method.
  37. /// </summary>
  38. /// <param name="formulaName">String which represent a formula name</param>
  39. /// <param name="inputValues">Arrays of doubles - Input values</param>
  40. /// <param name="outputValues">Arrays of doubles - Output values</param>
  41. /// <param name="parameterList">Array of strings - Formula parameters</param>
  42. /// <param name="extraParameterList">Array of strings - Extra Formula parameters from DataManipulator object</param>
  43. /// <param name="outLabels">Array of strings - Used for Labels. Description for output results.</param>
  44. virtual public void Formula( string formulaName, double [][] inputValues, out double [][] outputValues, string [] parameterList, string [] extraParameterList, out string [][] outLabels )
  45. {
  46. string name;
  47. outLabels = null;
  48. name = formulaName.ToUpper(System.Globalization.CultureInfo.InvariantCulture);
  49. try
  50. {
  51. switch( name )
  52. {
  53. case "TTESTEQUALVARIANCES":
  54. TTest( inputValues, out outputValues, parameterList, out outLabels, true );
  55. break;
  56. case "TTESTUNEQUALVARIANCES":
  57. TTest( inputValues, out outputValues, parameterList, out outLabels, false );
  58. break;
  59. case "TTESTPAIRED":
  60. TTestPaired( inputValues, out outputValues, parameterList, out outLabels );
  61. break;
  62. case "ZTEST":
  63. ZTest( inputValues, out outputValues, parameterList, out outLabels );
  64. break;
  65. case "FTEST":
  66. FTest( inputValues, out outputValues, parameterList, out outLabels );
  67. break;
  68. case "COVARIANCE":
  69. Covariance( inputValues, out outputValues, out outLabels );
  70. break;
  71. case "CORRELATION":
  72. Correlation( inputValues, out outputValues, out outLabels );
  73. break;
  74. case "ANOVA":
  75. Anova( inputValues, out outputValues, parameterList, out outLabels );
  76. break;
  77. case "TDISTRIBUTION":
  78. TDistribution( out outputValues, parameterList, out outLabels );
  79. break;
  80. case "FDISTRIBUTION":
  81. FDistribution( out outputValues, parameterList, out outLabels );
  82. break;
  83. case "NORMALDISTRIBUTION":
  84. NormalDistribution( out outputValues, parameterList, out outLabels );
  85. break;
  86. case "INVERSETDISTRIBUTION":
  87. TDistributionInverse( out outputValues, parameterList, out outLabels );
  88. break;
  89. case "INVERSEFDISTRIBUTION":
  90. FDistributionInverse( out outputValues, parameterList, out outLabels );
  91. break;
  92. case "INVERSENORMALDISTRIBUTION":
  93. NormalDistributionInverse( out outputValues, parameterList, out outLabels );
  94. break;
  95. case "MEAN":
  96. Average( inputValues, out outputValues, out outLabels );
  97. break;
  98. case "VARIANCE":
  99. Variance( inputValues, out outputValues, parameterList, out outLabels );
  100. break;
  101. case "MEDIAN":
  102. Median( inputValues, out outputValues, out outLabels );
  103. break;
  104. case "BETAFUNCTION":
  105. BetaFunction( out outputValues, parameterList, out outLabels );
  106. break;
  107. case "GAMMAFUNCTION":
  108. GammaFunction( out outputValues, parameterList, out outLabels );
  109. break;
  110. default:
  111. outputValues = null;
  112. break;
  113. }
  114. }
  115. catch( IndexOutOfRangeException )
  116. {
  117. throw new InvalidOperationException( SR.ExceptionFormulaInvalidPeriod(name) );
  118. }
  119. catch( OverflowException )
  120. {
  121. throw new InvalidOperationException( SR.ExceptionFormulaNotEnoughDataPoints(name) );
  122. }
  123. }
  124. #endregion // Methods
  125. #region Statistical Tests
  126. /// <summary>
  127. /// Anova test
  128. /// </summary>
  129. /// <param name="inputValues">Arrays of doubles - Input values</param>
  130. /// <param name="outputValues">Arrays of doubles - Output values</param>
  131. /// <param name="parameterList">Array of strings - Parameters</param>
  132. /// <param name="outLabels">Array of strings - Used for Labels. Description for output results.</param>
  133. private void Anova(double [][] inputValues, out double [][] outputValues, string [] parameterList, out string [][] outLabels )
  134. {
  135. // There is no enough input series
  136. if( inputValues.Length < 3 )
  137. throw new ArgumentException(SR.ExceptionStatisticalAnalysesNotEnoughInputSeries);
  138. outLabels = null;
  139. for( int index = 0; index < inputValues.Length - 1; index++ )
  140. {
  141. if( inputValues[index].Length != inputValues[index+1].Length )
  142. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidAnovaTest);
  143. }
  144. // Alpha value
  145. double alpha;
  146. try
  147. {
  148. alpha = double.Parse( parameterList[0], System.Globalization.CultureInfo.InvariantCulture );
  149. }
  150. catch(System.Exception)
  151. {
  152. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidAlphaValue);
  153. }
  154. if( alpha < 0 || alpha > 1 )
  155. {
  156. throw new ArgumentOutOfRangeException(SR.ExceptionStatisticalAnalysesInvalidAlphaValue);
  157. }
  158. // Output arrays
  159. outputValues = new double [2][];
  160. // Output Labels
  161. outLabels = new string [1][];
  162. // Parameters description
  163. outLabels[0] = new string [10];
  164. // X
  165. outputValues[0] = new double [10];
  166. // Y
  167. outputValues[1] = new double [10];
  168. int m = inputValues.Length - 1;
  169. int n = inputValues[0].Length;
  170. double [] average = new double[ m ];
  171. double [] variance = new double[ m ];
  172. // Find averages
  173. for( int group = 0; group < m; group++ )
  174. {
  175. average[group] = Mean( inputValues[group+1] );
  176. }
  177. // Find variances
  178. for( int group = 0; group < m; group++ )
  179. {
  180. variance[group] = Variance( inputValues[group+1], true );
  181. }
  182. // Total Average ( for all groups )
  183. double averageTotal = Mean( average );
  184. // Total Sample Variance
  185. double totalS = 0;
  186. foreach( double avr in average )
  187. {
  188. totalS += ( avr - averageTotal ) * ( avr - averageTotal );
  189. }
  190. totalS /= ( m - 1 );
  191. // Group Sample Variance
  192. double groupS = Mean( variance );
  193. // F Statistica
  194. double f = totalS * ( n ) / groupS;
  195. // ****************************************
  196. // Sum of Squares
  197. // ****************************************
  198. // Grend Total Average
  199. double grandTotalAverage = 0;
  200. for( int group = 0; group < m; group++ )
  201. {
  202. foreach( double point in inputValues[group+1] )
  203. {
  204. grandTotalAverage += point;
  205. }
  206. }
  207. grandTotalAverage /= ( m * n );
  208. // Treatment Sum of Squares
  209. double trss = 0;
  210. for( int group = 0; group < m; group++ )
  211. {
  212. trss += ( average[group] - grandTotalAverage ) * ( average[group] - grandTotalAverage );
  213. }
  214. trss *= n;
  215. // Error Sum of Squares
  216. double erss = 0;
  217. for( int group = 0; group < m; group++ )
  218. {
  219. foreach( double point in inputValues[group+1] )
  220. {
  221. erss += ( point - average[group] ) * ( point - average[group] );
  222. }
  223. }
  224. outLabels[0][0] = SR.LabelStatisticalSumOfSquaresBetweenGroups;
  225. outputValues[0][0] = 1;
  226. outputValues[1][0] = trss;
  227. outLabels[0][1] = SR.LabelStatisticalSumOfSquaresWithinGroups;
  228. outputValues[0][1] = 2;
  229. outputValues[1][1] = erss;
  230. outLabels[0][2] = SR.LabelStatisticalSumOfSquaresTotal;
  231. outputValues[0][2] = 3;
  232. outputValues[1][2] = trss + erss;
  233. outLabels[0][3] = SR.LabelStatisticalDegreesOfFreedomBetweenGroups;
  234. outputValues[0][3] = 4;
  235. outputValues[1][3] = m - 1;
  236. outLabels[0][4] = SR.LabelStatisticalDegreesOfFreedomWithinGroups;
  237. outputValues[0][4] = 5;
  238. outputValues[1][4] = m * ( n - 1 );
  239. outLabels[0][5] = SR.LabelStatisticalDegreesOfFreedomTotal;
  240. outputValues[0][5] = 6;
  241. outputValues[1][5] = m * n - 1;
  242. outLabels[0][6] = SR.LabelStatisticalMeanSquareVarianceBetweenGroups;
  243. outputValues[0][6] = 7;
  244. outputValues[1][6] = trss / ( m - 1 );
  245. outLabels[0][7] = SR.LabelStatisticalMeanSquareVarianceWithinGroups;
  246. outputValues[0][7] = 8;
  247. outputValues[1][7] = erss / ( m * ( n - 1 ) );
  248. outLabels[0][8] = SR.LabelStatisticalFRatio;
  249. outputValues[0][8] = 9;
  250. outputValues[1][8] = f;
  251. outLabels[0][9] = SR.LabelStatisticalFCriteria;
  252. outputValues[0][9] = 10;
  253. outputValues[1][9] = FDistributionInverse( alpha, m - 1, m * ( n - 1 ) );
  254. }
  255. /// <summary>
  256. /// Correlation measure the relationship between two data sets that
  257. /// are scaled to be independent of the unit of measurement. The
  258. /// population correlation calculation returns the covariance
  259. /// of two data sets divided by the product of their standard
  260. /// deviations: You can use the Correlation to determine whether two
  261. /// ranges of data move together — that is, whether large values of
  262. /// one set are associated with large values of the other
  263. /// (positive correlation), whether small values of one set are
  264. /// associated with large values of the other (negative correlation),
  265. /// or whether values in both sets are unrelated (correlation
  266. /// near zero).
  267. /// </summary>
  268. /// <param name="inputValues">Arrays of doubles - Input values</param>
  269. /// <param name="outputValues">Arrays of doubles - Output values</param>
  270. /// <param name="outLabels">Array of strings - Used for Labels. Description for output results.</param>
  271. private void Correlation(double [][] inputValues, out double [][] outputValues, out string [][] outLabels )
  272. {
  273. // There is no enough input series
  274. if( inputValues.Length != 3 )
  275. throw new ArgumentException( SR.ExceptionPriceIndicatorsFormulaRequiresTwoArrays);
  276. outLabels = null;
  277. // Output arrays
  278. outputValues = new double [2][];
  279. // Output Labels
  280. outLabels = new string [1][];
  281. // Parameters description
  282. outLabels[0] = new string [1];
  283. // X
  284. outputValues[0] = new double [1];
  285. // Y
  286. outputValues[1] = new double [1];
  287. // Find Covariance.
  288. double covar = Covar( inputValues[1], inputValues[2] );
  289. double varianceX = Variance( inputValues[1], false );
  290. double varianceY = Variance( inputValues[2], false );
  291. // Correlation
  292. double correl = covar / Math.Sqrt( varianceX * varianceY );
  293. outLabels[0][0] = SR.LabelStatisticalCorrelation;
  294. outputValues[0][0] = 1;
  295. outputValues[1][0] = correl;
  296. }
  297. /// <summary>
  298. /// Returns covariance, the average of the products of deviations
  299. /// for each data point pair. Use covariance to determine the
  300. /// relationship between two data sets. For example, you can
  301. /// examine whether greater income accompanies greater
  302. /// levels of education.
  303. /// </summary>
  304. /// <param name="inputValues">Arrays of doubles - Input values</param>
  305. /// <param name="outputValues">Arrays of doubles - Output values</param>
  306. /// <param name="outLabels">Array of strings - Used for Labels. Description for output results.</param>
  307. private void Covariance(double [][] inputValues, out double [][] outputValues, out string [][] outLabels )
  308. {
  309. // There is no enough input series
  310. if( inputValues.Length != 3 )
  311. throw new ArgumentException( SR.ExceptionPriceIndicatorsFormulaRequiresTwoArrays);
  312. outLabels = null;
  313. // Output arrays
  314. outputValues = new double [2][];
  315. // Output Labels
  316. outLabels = new string [1][];
  317. // Parameters description
  318. outLabels[0] = new string [1];
  319. // X
  320. outputValues[0] = new double [1];
  321. // Y
  322. outputValues[1] = new double [1];
  323. // Find Covariance.
  324. double covar = Covar( inputValues[1], inputValues[2] );
  325. outLabels[0][0] = SR.LabelStatisticalCovariance;
  326. outputValues[0][0] = 1;
  327. outputValues[1][0] = covar;
  328. }
  329. /// <summary>
  330. /// Returns the result of an F-test. An F-test returns the one-tailed
  331. /// probability that the variances in array1 and array2 are not
  332. /// significantly different. Use this function to determine
  333. /// whether two samples have different variances. For example,
  334. /// given test scores from public and private schools, you can
  335. /// test whether these schools have different levels of diversity.
  336. /// </summary>
  337. /// <param name="inputValues">Arrays of doubles - Input values</param>
  338. /// <param name="outputValues">Arrays of doubles - Output values</param>
  339. /// <param name="parameterList">Array of strings - Parameters</param>
  340. /// <param name="outLabels">Array of strings - Used for Labels. Description for output results.</param>
  341. private void FTest(double [][] inputValues, out double [][] outputValues, string [] parameterList, out string [][] outLabels )
  342. {
  343. // There is no enough input series
  344. if( inputValues.Length != 3 )
  345. throw new ArgumentException( SR.ExceptionPriceIndicatorsFormulaRequiresTwoArrays);
  346. outLabels = null;
  347. double alpha;
  348. // The number of data points has to be > 1.
  349. CheckNumOfPoints( inputValues );
  350. // Alpha value
  351. try
  352. {
  353. alpha = double.Parse( parameterList[0], System.Globalization.CultureInfo.InvariantCulture );
  354. }
  355. catch(System.Exception)
  356. {
  357. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidAlphaValue);
  358. }
  359. if( alpha < 0 || alpha > 1 )
  360. {
  361. throw new ArgumentOutOfRangeException(SR.ExceptionStatisticalAnalysesInvalidAlphaValue);
  362. }
  363. // Output arrays
  364. outputValues = new double [2][];
  365. // Output Labels
  366. outLabels = new string [1][];
  367. // Parameters description
  368. outLabels[0] = new string [7];
  369. // X
  370. outputValues[0] = new double [7];
  371. // Y
  372. outputValues[1] = new double [7];
  373. // Find Variance of the first group
  374. double variance1 = Variance( inputValues[1], true );
  375. // Find Variance of the second group
  376. double variance2 = Variance( inputValues[2], true );
  377. // Find Mean of the first group
  378. double mean1 = Mean( inputValues[1] );
  379. // Find Mean of the second group
  380. double mean2 = Mean( inputValues[2] );
  381. // F Value
  382. double valueF = variance1 / variance2;
  383. if( variance2 == 0 )
  384. {
  385. throw new InvalidOperationException(SR.ExceptionStatisticalAnalysesZeroVariance);
  386. }
  387. // The way to find a left critical value is to reversed the degrees of freedom,
  388. // look up the right critical value, and then take the reciprocal of this value.
  389. // For example, the critical value with 0.05 on the left with 12 numerator and 15
  390. // denominator degrees of freedom is found of taking the reciprocal of the critical
  391. // value with 0.05 on the right with 15 numerator and 12 denominator degrees of freedom.
  392. // Avoiding Left Critical Values. Since the left critical values are a pain to calculate,
  393. // they are often avoided altogether. This is the procedure followed in the textbook.
  394. // You can force the F test into a right tail test by placing the sample with the large
  395. // variance in the numerator and the smaller variance in the denominator. It does not
  396. // matter which sample has the larger sample size, only which sample has the larger
  397. // variance. The numerator degrees of freedom will be the degrees of freedom for
  398. // whichever sample has the larger variance (since it is in the numerator) and the
  399. // denominator degrees of freedom will be the degrees of freedom for whichever sample
  400. // has the smaller variance (since it is in the denominator).
  401. bool lessOneF = valueF <= 1;
  402. double fDistInv;
  403. double fDist;
  404. if( lessOneF )
  405. {
  406. fDistInv = FDistributionInverse( 1 - alpha, inputValues[1].Length - 1, inputValues[2].Length - 1 );
  407. fDist = 1 - FDistribution( valueF, inputValues[1].Length - 1, inputValues[2].Length - 1 );
  408. }
  409. else
  410. {
  411. fDistInv = FDistributionInverse( alpha, inputValues[1].Length - 1, inputValues[2].Length - 1 );
  412. fDist = FDistribution( valueF, inputValues[1].Length - 1, inputValues[2].Length - 1 );
  413. }
  414. outLabels[0][0] = SR.LabelStatisticalTheFirstGroupMean;
  415. outputValues[0][0] = 1;
  416. outputValues[1][0] = mean1;
  417. outLabels[0][1] = SR.LabelStatisticalTheSecondGroupMean;
  418. outputValues[0][1] = 2;
  419. outputValues[1][1] = mean2;
  420. outLabels[0][2] = SR.LabelStatisticalTheFirstGroupVariance;
  421. outputValues[0][2] = 3;
  422. outputValues[1][2] = variance1;
  423. outLabels[0][3] = SR.LabelStatisticalTheSecondGroupVariance;
  424. outputValues[0][3] = 4;
  425. outputValues[1][3] = variance2;
  426. outLabels[0][4] = SR.LabelStatisticalFValue;
  427. outputValues[0][4] = 5;
  428. outputValues[1][4] = valueF;
  429. outLabels[0][5] = SR.LabelStatisticalPFLessEqualSmallFOneTail;
  430. outputValues[0][5] = 6;
  431. outputValues[1][5] = fDist;
  432. outLabels[0][6] = SR.LabelStatisticalFCriticalValueOneTail;
  433. outputValues[0][6] = 7;
  434. outputValues[1][6] = fDistInv;
  435. }
  436. /// <summary>
  437. /// Returns the two-tailed P-value of a z-test. The z-test
  438. /// generates a standard score for x with respect to the data set,
  439. /// array, and returns the two-tailed probability for the
  440. /// normal distribution. You can use this function to assess
  441. /// the likelihood that a particular observation is drawn
  442. /// from a particular population.
  443. /// </summary>
  444. /// <param name="inputValues">Arrays of doubles - Input values</param>
  445. /// <param name="outputValues">Arrays of doubles - Output values</param>
  446. /// <param name="parameterList">Array of strings - Parameters</param>
  447. /// <param name="outLabels">Array of strings - Used for Labels. Description for output results.</param>
  448. private void ZTest(double [][] inputValues, out double [][] outputValues, string [] parameterList, out string [][] outLabels )
  449. {
  450. // There is no enough input series
  451. if( inputValues.Length != 3 )
  452. throw new ArgumentException( SR.ExceptionPriceIndicatorsFormulaRequiresTwoArrays);
  453. // The number of data points has to be > 1.
  454. CheckNumOfPoints( inputValues );
  455. outLabels = null;
  456. double variance1;
  457. double variance2;
  458. double alpha;
  459. double HypothesizedMeanDifference;
  460. // Find Hypothesized Mean Difference parameter
  461. try
  462. {
  463. HypothesizedMeanDifference = double.Parse( parameterList[0], System.Globalization.CultureInfo.InvariantCulture );
  464. }
  465. catch(System.Exception)
  466. {
  467. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidMeanDifference);
  468. }
  469. if( HypothesizedMeanDifference < 0.0 )
  470. {
  471. throw new ArgumentOutOfRangeException(SR.ExceptionStatisticalAnalysesNegativeMeanDifference);
  472. }
  473. // Find variance of the first group
  474. try
  475. {
  476. variance1 = double.Parse( parameterList[1], System.Globalization.CultureInfo.InvariantCulture );
  477. }
  478. catch(System.Exception)
  479. {
  480. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidVariance);
  481. }
  482. // Find variance of the second group
  483. try
  484. {
  485. variance2 = double.Parse( parameterList[2], System.Globalization.CultureInfo.InvariantCulture );
  486. }
  487. catch(System.Exception)
  488. {
  489. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidVariance);
  490. }
  491. // Alpha value
  492. try
  493. {
  494. alpha = double.Parse( parameterList[3], System.Globalization.CultureInfo.InvariantCulture );
  495. }
  496. catch(System.Exception)
  497. {
  498. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidAlphaValue);
  499. }
  500. if( alpha < 0 || alpha > 1 )
  501. {
  502. throw new ArgumentOutOfRangeException(SR.ExceptionStatisticalAnalysesInvalidAlphaValue);
  503. }
  504. // Output arrays
  505. outputValues = new double [2][];
  506. // Output Labels
  507. outLabels = new string [1][];
  508. // Parameters description
  509. outLabels[0] = new string [9];
  510. // X
  511. outputValues[0] = new double [9];
  512. // Y
  513. outputValues[1] = new double [9];
  514. // Find Mean of the first group
  515. double mean1 = Mean( inputValues[1] );
  516. // Find Mean of the second group
  517. double mean2 = Mean( inputValues[2] );
  518. double dev = Math.Sqrt( variance1 / inputValues[1].Length + variance2 / inputValues[2].Length );
  519. // Z Value
  520. double valueZ = ( mean1 - mean2 - HypothesizedMeanDifference ) / dev;
  521. double normalDistTwoInv = NormalDistributionInverse( 1 - alpha / 2 );
  522. double normalDistOneInv = NormalDistributionInverse( 1 - alpha);
  523. double normalDistOne;
  524. double normalDistTwo;
  525. if( valueZ < 0.0 )
  526. {
  527. normalDistOne = NormalDistribution( valueZ );
  528. }
  529. else
  530. {
  531. normalDistOne = 1.0 - NormalDistribution( valueZ );
  532. }
  533. normalDistTwo = 2.0 * normalDistOne;
  534. outLabels[0][0] = SR.LabelStatisticalTheFirstGroupMean;
  535. outputValues[0][0] = 1;
  536. outputValues[1][0] = mean1;
  537. outLabels[0][1] = SR.LabelStatisticalTheSecondGroupMean;
  538. outputValues[0][1] = 2;
  539. outputValues[1][1] = mean2;
  540. outLabels[0][2] = SR.LabelStatisticalTheFirstGroupVariance;
  541. outputValues[0][2] = 3;
  542. outputValues[1][2] = variance1;
  543. outLabels[0][3] = SR.LabelStatisticalTheSecondGroupVariance;
  544. outputValues[0][3] = 4;
  545. outputValues[1][3] = variance2;
  546. outLabels[0][4] = SR.LabelStatisticalZValue;
  547. outputValues[0][4] = 5;
  548. outputValues[1][4] = valueZ;
  549. outLabels[0][5] = SR.LabelStatisticalPZLessEqualSmallZOneTail;
  550. outputValues[0][5] = 6;
  551. outputValues[1][5] = normalDistOne;
  552. outLabels[0][6] = SR.LabelStatisticalZCriticalValueOneTail;
  553. outputValues[0][6] = 7;
  554. outputValues[1][6] = normalDistOneInv;
  555. outLabels[0][7] = SR.LabelStatisticalPZLessEqualSmallZTwoTail;
  556. outputValues[0][7] = 8;
  557. outputValues[1][7] = normalDistTwo;
  558. outLabels[0][8] = SR.LabelStatisticalZCriticalValueTwoTail;
  559. outputValues[0][8] = 9;
  560. outputValues[1][8] = normalDistTwoInv;
  561. }
  562. /// <summary>
  563. /// Returns the two-tailed P-value of a z-test. The z-test
  564. /// generates a standard score for x with respect to the data set,
  565. /// array, and returns the two-tailed probability for the
  566. /// normal distribution. You can use this function to assess
  567. /// the likelihood that a particular observation is drawn
  568. /// from a particular population.
  569. /// </summary>
  570. /// <param name="inputValues">Arrays of doubles - Input values</param>
  571. /// <param name="outputValues">Arrays of doubles - Output values</param>
  572. /// <param name="parameterList">Array of strings - Parameters</param>
  573. /// <param name="outLabels">Array of strings - Used for Labels. Description for output results.</param>
  574. /// <param name="equalVariances">True if Variances are equal.</param>
  575. private void TTest(double [][] inputValues, out double [][] outputValues, string [] parameterList, out string [][] outLabels, bool equalVariances )
  576. {
  577. // There is no enough input series
  578. if( inputValues.Length != 3 )
  579. throw new ArgumentException( SR.ExceptionPriceIndicatorsFormulaRequiresTwoArrays);
  580. outLabels = null;
  581. double variance1;
  582. double variance2;
  583. double alpha;
  584. double HypothesizedMeanDifference;
  585. // Find Hypothesized Mean Difference parameter
  586. try
  587. {
  588. HypothesizedMeanDifference = double.Parse( parameterList[0], System.Globalization.CultureInfo.InvariantCulture );
  589. }
  590. catch(System.Exception)
  591. {
  592. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidMeanDifference);
  593. }
  594. if( HypothesizedMeanDifference < 0.0 )
  595. {
  596. throw new ArgumentOutOfRangeException(SR.ExceptionStatisticalAnalysesNegativeMeanDifference);
  597. }
  598. // Alpha value
  599. try
  600. {
  601. alpha = double.Parse( parameterList[1], System.Globalization.CultureInfo.InvariantCulture );
  602. }
  603. catch(System.Exception)
  604. {
  605. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidAlphaValue);
  606. }
  607. if( alpha < 0 || alpha > 1 )
  608. {
  609. throw new ArgumentOutOfRangeException(SR.ExceptionStatisticalAnalysesInvalidAlphaValue);
  610. }
  611. // The number of data points has to be > 1.
  612. CheckNumOfPoints( inputValues );
  613. // Output arrays
  614. outputValues = new double [2][];
  615. // Output Labels
  616. outLabels = new string [1][];
  617. // Parameters description
  618. outLabels[0] = new string [10];
  619. // X
  620. outputValues[0] = new double [10];
  621. // Y
  622. outputValues[1] = new double [10];
  623. // Find Mean of the first group
  624. double mean1 = Mean( inputValues[1] );
  625. // Find Mean of the second group
  626. double mean2 = Mean( inputValues[2] );
  627. variance1 = Variance( inputValues[1], true );
  628. variance2 = Variance( inputValues[2], true );
  629. double s;
  630. double T;
  631. int freedom;
  632. if( equalVariances )
  633. {
  634. freedom = inputValues[1].Length + inputValues[2].Length - 2;
  635. // S value
  636. s = ( ( inputValues[1].Length - 1 ) * variance1 + ( inputValues[2].Length - 1 ) * variance2 ) / ( inputValues[1].Length + inputValues[2].Length - 2 );
  637. // T value
  638. T = ( mean1 - mean2 - HypothesizedMeanDifference ) / ( Math.Sqrt( s * ( 1.0 / inputValues[1].Length + 1.0 / inputValues[2].Length ) ) );
  639. }
  640. else
  641. {
  642. double m = inputValues[1].Length;
  643. double n = inputValues[2].Length;
  644. double s1 = variance1;
  645. double s2 = variance2;
  646. double f = ( s1 / m + s2 / n ) * ( s1 / m + s2 / n ) / ( ( s1 / m ) * ( s1 / m ) / ( m - 1 ) + ( s2 / n ) * ( s2 / n ) / ( n - 1 ) );
  647. freedom = (int)Math.Round(f);
  648. s = Math.Sqrt( variance1 / inputValues[1].Length + variance2 / inputValues[2].Length );
  649. // Z Value
  650. T = ( mean1 - mean2 - HypothesizedMeanDifference ) / s;
  651. }
  652. double TDistTwoInv = StudentsDistributionInverse( alpha , freedom );
  653. bool more50 = alpha > 0.5;
  654. if( more50 )
  655. {
  656. alpha = 1 - alpha;
  657. }
  658. double TDistOneInv = StudentsDistributionInverse( alpha * 2.0, freedom );
  659. if( more50 )
  660. {
  661. TDistOneInv *= -1.0;
  662. }
  663. double TDistTwo = StudentsDistribution( T, freedom, false );
  664. double TDistOne = StudentsDistribution( T, freedom, true );
  665. outLabels[0][0] = SR.LabelStatisticalTheFirstGroupMean;
  666. outputValues[0][0] = 1;
  667. outputValues[1][0] = mean1;
  668. outLabels[0][1] = SR.LabelStatisticalTheSecondGroupMean;
  669. outputValues[0][1] = 2;
  670. outputValues[1][1] = mean2;
  671. outLabels[0][2] = SR.LabelStatisticalTheFirstGroupVariance;
  672. outputValues[0][2] = 3;
  673. outputValues[1][2] = variance1;
  674. outLabels[0][3] = SR.LabelStatisticalTheSecondGroupVariance;
  675. outputValues[0][3] = 4;
  676. outputValues[1][3] = variance2;
  677. outLabels[0][4] = SR.LabelStatisticalTValue;
  678. outputValues[0][4] = 5;
  679. outputValues[1][4] = T;
  680. outLabels[0][5] = SR.LabelStatisticalDegreeOfFreedom;
  681. outputValues[0][5] = 6;
  682. outputValues[1][5] = freedom;
  683. outLabels[0][6] = SR.LabelStatisticalPTLessEqualSmallTOneTail;
  684. outputValues[0][6] = 7;
  685. outputValues[1][6] = TDistOne;
  686. outLabels[0][7] = SR.LabelStatisticalSmallTCrititcalOneTail;
  687. outputValues[0][7] = 8;
  688. outputValues[1][7] = TDistOneInv;
  689. outLabels[0][8] = SR.LabelStatisticalPTLessEqualSmallTTwoTail;
  690. outputValues[0][8] = 9;
  691. outputValues[1][8] = TDistTwo;
  692. outLabels[0][9] = SR.LabelStatisticalSmallTCrititcalTwoTail;
  693. outputValues[0][9] = 10;
  694. outputValues[1][9] = TDistTwoInv;
  695. }
  696. /// <summary>
  697. /// Returns the two-tailed P-value of a z-test. The z-test
  698. /// generates a standard score for x with respect to the data set,
  699. /// array, and returns the two-tailed probability for the
  700. /// normal distribution. You can use this function to assess
  701. /// the likelihood that a particular observation is drawn
  702. /// from a particular population.
  703. /// </summary>
  704. /// <param name="inputValues">Arrays of doubles - Input values</param>
  705. /// <param name="outputValues">Arrays of doubles - Output values</param>
  706. /// <param name="parameterList">Array of strings - Parameters</param>
  707. /// <param name="outLabels">Array of strings - Used for Labels. Description for output results.</param>
  708. private void TTestPaired(double [][] inputValues, out double [][] outputValues, string [] parameterList, out string [][] outLabels )
  709. {
  710. // There is no enough input series
  711. if( inputValues.Length != 3 )
  712. throw new ArgumentException( SR.ExceptionPriceIndicatorsFormulaRequiresTwoArrays);
  713. if( inputValues[1].Length != inputValues[2].Length )
  714. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidVariableRanges);
  715. outLabels = null;
  716. double variance;
  717. double alpha;
  718. double HypothesizedMeanDifference;
  719. int freedom;
  720. // Find Hypothesized Mean Difference parameter
  721. try
  722. {
  723. HypothesizedMeanDifference = double.Parse( parameterList[0], System.Globalization.CultureInfo.InvariantCulture );
  724. }
  725. catch(System.Exception)
  726. {
  727. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidMeanDifference);
  728. }
  729. if( HypothesizedMeanDifference < 0.0 )
  730. {
  731. throw new ArgumentOutOfRangeException(SR.ExceptionStatisticalAnalysesNegativeMeanDifference);
  732. }
  733. // Alpha value
  734. try
  735. {
  736. alpha = double.Parse( parameterList[1], System.Globalization.CultureInfo.InvariantCulture );
  737. }
  738. catch(System.Exception)
  739. {
  740. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidAlphaValue);
  741. }
  742. if( alpha < 0 || alpha > 1 )
  743. {
  744. throw new ArgumentOutOfRangeException(SR.ExceptionStatisticalAnalysesInvalidAlphaValue);
  745. }
  746. // The number of data points has to be > 1.
  747. CheckNumOfPoints( inputValues );
  748. // Output arrays
  749. outputValues = new double [2][];
  750. // Output Labels
  751. outLabels = new string [1][];
  752. // Parameters description
  753. outLabels[0] = new string [10];
  754. // X
  755. outputValues[0] = new double [10];
  756. // Y
  757. outputValues[1] = new double [10];
  758. double [] difference = new double[inputValues[1].Length];
  759. for( int item = 0; item < inputValues[1].Length; item++ )
  760. {
  761. difference[item] = inputValues[1][item] - inputValues[2][item];
  762. }
  763. // Find Mean of the second group
  764. double mean = Mean( difference );
  765. variance = Math.Sqrt( Variance( difference, true ) );
  766. double T = ( Math.Sqrt( inputValues[1].Length ) * ( mean - HypothesizedMeanDifference ) ) / variance;
  767. freedom = inputValues[1].Length - 1;
  768. double TDistTwoInv = StudentsDistributionInverse( alpha , freedom );
  769. double TDistOneInv = alpha <= 0.5 ? StudentsDistributionInverse(2 * alpha, freedom) : double.NaN;
  770. double TDistTwo = StudentsDistribution( T, freedom, false );
  771. double TDistOne = StudentsDistribution( T, freedom, true );
  772. outLabels[0][0] = SR.LabelStatisticalTheFirstGroupMean;
  773. outputValues[0][0] = 1;
  774. outputValues[1][0] = Mean(inputValues[1]);
  775. outLabels[0][1] = SR.LabelStatisticalTheSecondGroupMean;
  776. outputValues[0][1] = 2;
  777. outputValues[1][1] = Mean(inputValues[2]);
  778. outLabels[0][2] = SR.LabelStatisticalTheFirstGroupVariance;
  779. outputValues[0][2] = 3;
  780. outputValues[1][2] = Variance(inputValues[1],true);
  781. outLabels[0][3] = SR.LabelStatisticalTheSecondGroupVariance;
  782. outputValues[0][3] = 4;
  783. outputValues[1][3] = Variance(inputValues[2],true);
  784. outLabels[0][4] = SR.LabelStatisticalTValue;
  785. outputValues[0][4] = 5;
  786. outputValues[1][4] = T;
  787. outLabels[0][5] = SR.LabelStatisticalDegreeOfFreedom;
  788. outputValues[0][5] = 6;
  789. outputValues[1][5] = freedom;
  790. outLabels[0][6] = SR.LabelStatisticalPTLessEqualSmallTOneTail;
  791. outputValues[0][6] = 7;
  792. outputValues[1][6] = TDistOne;
  793. outLabels[0][7] = SR.LabelStatisticalSmallTCrititcalOneTail;
  794. outputValues[0][7] = 8;
  795. outputValues[1][7] = TDistOneInv;
  796. outLabels[0][8] = SR.LabelStatisticalPTLessEqualSmallTTwoTail;
  797. outputValues[0][8] = 9;
  798. outputValues[1][8] = TDistTwo;
  799. outLabels[0][9] = SR.LabelStatisticalSmallTCrititcalTwoTail;
  800. outputValues[0][9] = 10;
  801. outputValues[1][9] = TDistTwoInv;
  802. }
  803. #endregion // Statistical Tests
  804. #region Public distributions
  805. /// <summary>
  806. /// Returns the Percentage Points (probability) for the Student
  807. /// t-distribution. The t-distribution is used in the hypothesis
  808. /// testing of small sample data sets. Use this function in place
  809. /// of a table of critical values for the t-distribution.
  810. /// </summary>
  811. /// <param name="outputValues">Arrays of doubles - Output values</param>
  812. /// <param name="parameterList">Array of strings - Parameters</param>
  813. /// <param name="outLabels">Array of strings - Used for Labels. Description for output results.</param>
  814. private void TDistribution(out double [][] outputValues, string [] parameterList, out string [][] outLabels )
  815. {
  816. // T value value
  817. double tValue;
  818. try
  819. {
  820. tValue = double.Parse( parameterList[0], System.Globalization.CultureInfo.InvariantCulture );
  821. }
  822. catch(System.Exception)
  823. {
  824. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidTValue);
  825. }
  826. // DegreeOfFreedom
  827. int freedom;
  828. try
  829. {
  830. freedom = int.Parse( parameterList[1], System.Globalization.CultureInfo.InvariantCulture );
  831. }
  832. catch(System.Exception)
  833. {
  834. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidDegreeOfFreedom);
  835. }
  836. // One Tailed distribution
  837. int oneTailed;
  838. try
  839. {
  840. oneTailed = int.Parse( parameterList[2], System.Globalization.CultureInfo.InvariantCulture );
  841. }
  842. catch(System.Exception)
  843. {
  844. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidTailedParameter);
  845. }
  846. outLabels = null;
  847. // Output arrays
  848. outputValues = new double [2][];
  849. // Output Labels
  850. outLabels = new string [1][];
  851. // Parameters description
  852. outLabels[0] = new string [1];
  853. // X
  854. outputValues[0] = new double [1];
  855. // Y
  856. outputValues[1] = new double [1];
  857. outLabels[0][0] = SR.LabelStatisticalProbability;
  858. outputValues[0][0] = 1;
  859. outputValues[1][0] = StudentsDistribution( tValue, freedom, oneTailed == 1 );
  860. }
  861. /// <summary>
  862. /// Returns the F probability distribution. You can use
  863. /// this function to determine whether two data sets have
  864. /// different degrees of diversity. For example, you can
  865. /// examine test scores given to men and women entering
  866. /// high school and determine if the variability in the
  867. /// females is different from that found in the males.
  868. /// </summary>
  869. /// <param name="outputValues">Arrays of doubles - Output values</param>
  870. /// <param name="parameterList">Array of strings - Parameters</param>
  871. /// <param name="outLabels">Array of strings - Used for Labels. Description for output results.</param>
  872. private void FDistribution(out double [][] outputValues, string [] parameterList, out string [][] outLabels )
  873. {
  874. // F value value
  875. double fValue;
  876. try
  877. {
  878. fValue = double.Parse( parameterList[0], System.Globalization.CultureInfo.InvariantCulture );
  879. }
  880. catch(System.Exception)
  881. {
  882. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidTValue);
  883. }
  884. // Degree Of Freedom 1
  885. int freedom1;
  886. try
  887. {
  888. freedom1 = int.Parse( parameterList[1], System.Globalization.CultureInfo.InvariantCulture );
  889. }
  890. catch(System.Exception)
  891. {
  892. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidDegreeOfFreedom);
  893. }
  894. // Degree Of Freedom 2
  895. int freedom2;
  896. try
  897. {
  898. freedom2 = int.Parse( parameterList[2], System.Globalization.CultureInfo.InvariantCulture );
  899. }
  900. catch(System.Exception)
  901. {
  902. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidDegreeOfFreedom);
  903. }
  904. outLabels = null;
  905. // Output arrays
  906. outputValues = new double [2][];
  907. // Output Labels
  908. outLabels = new string [1][];
  909. // Parameters description
  910. outLabels[0] = new string [1];
  911. // X
  912. outputValues[0] = new double [1];
  913. // Y
  914. outputValues[1] = new double [1];
  915. outLabels[0][0] = SR.LabelStatisticalProbability;
  916. outputValues[0][0] = 1;
  917. outputValues[1][0] = FDistribution( fValue, freedom1, freedom2 );
  918. }
  919. /// <summary></summary>
  920. /// <param name="outputValues">Arrays of doubles - Output values</param>
  921. /// <param name="parameterList">Array of strings - Parameters</param>
  922. /// <param name="outLabels">Array of strings - Used for Labels. Description for output results.</param>
  923. private void NormalDistribution(out double [][] outputValues, string [] parameterList, out string [][] outLabels )
  924. {
  925. // F value value
  926. double zValue;
  927. try
  928. {
  929. zValue = double.Parse( parameterList[0], System.Globalization.CultureInfo.InvariantCulture );
  930. }
  931. catch(System.Exception)
  932. {
  933. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidZValue);
  934. }
  935. outLabels = null;
  936. // Output arrays
  937. outputValues = new double [2][];
  938. // Output Labels
  939. outLabels = new string [1][];
  940. // Parameters description
  941. outLabels[0] = new string [1];
  942. // X
  943. outputValues[0] = new double [1];
  944. // Y
  945. outputValues[1] = new double [1];
  946. outLabels[0][0] = SR.LabelStatisticalProbability;
  947. outputValues[0][0] = 1;
  948. outputValues[1][0] = this.NormalDistribution( zValue );
  949. }
  950. /// <summary>
  951. /// Returns the t-value of the Student's t-distribution
  952. /// as a function of the probability and the degrees
  953. /// of freedom.
  954. /// </summary>
  955. /// <param name="outputValues">Arrays of doubles - Output values</param>
  956. /// <param name="parameterList">Array of strings - Parameters</param>
  957. /// <param name="outLabels">Array of strings - Used for Labels. Description for output results.</param>
  958. private void TDistributionInverse(out double [][] outputValues, string [] parameterList, out string [][] outLabels )
  959. {
  960. // T value value
  961. double probability;
  962. try
  963. {
  964. probability = double.Parse( parameterList[0], System.Globalization.CultureInfo.InvariantCulture );
  965. }
  966. catch(System.Exception)
  967. {
  968. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidProbabilityValue);
  969. }
  970. // DegreeOfFreedom
  971. int freedom;
  972. try
  973. {
  974. freedom = int.Parse( parameterList[1], System.Globalization.CultureInfo.InvariantCulture );
  975. }
  976. catch(System.Exception)
  977. {
  978. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidDegreeOfFreedom);
  979. }
  980. outLabels = null;
  981. // Output arrays
  982. outputValues = new double [2][];
  983. // Output Labels
  984. outLabels = new string [1][];
  985. // Parameters description
  986. outLabels[0] = new string [1];
  987. // X
  988. outputValues[0] = new double [1];
  989. // Y
  990. outputValues[1] = new double [1];
  991. outLabels[0][0] = SR.LabelStatisticalProbability;
  992. outputValues[0][0] = 1;
  993. outputValues[1][0] = StudentsDistributionInverse( probability, freedom );
  994. }
  995. /// <summary>
  996. /// Returns the inverse of the F probability distribution.
  997. /// If p = FDIST(x,...), then FINV(p,...) = x. The F distribution
  998. /// can be used in an F-test that compares the degree of
  999. /// variability in two data sets. For example, you can analyze
  1000. /// income distributions in the United States and Canada to
  1001. /// determine whether the two countries have a similar degree
  1002. /// of diversity.
  1003. /// </summary>
  1004. /// <param name="outputValues">Arrays of doubles - Output values</param>
  1005. /// <param name="parameterList">Array of strings - Parameters</param>
  1006. /// <param name="outLabels">Array of strings - Used for Labels. Description for output results.</param>
  1007. private void FDistributionInverse(out double [][] outputValues, string [] parameterList, out string [][] outLabels )
  1008. {
  1009. // Probability value value
  1010. double probability;
  1011. try
  1012. {
  1013. probability = double.Parse( parameterList[0], System.Globalization.CultureInfo.InvariantCulture );
  1014. }
  1015. catch(System.Exception)
  1016. {
  1017. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidProbabilityValue);
  1018. }
  1019. // Degree Of Freedom 1
  1020. int freedom1;
  1021. try
  1022. {
  1023. freedom1 = int.Parse( parameterList[1], System.Globalization.CultureInfo.InvariantCulture );
  1024. }
  1025. catch(System.Exception)
  1026. {
  1027. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidDegreeOfFreedom);
  1028. }
  1029. // Degree Of Freedom 2
  1030. int freedom2;
  1031. try
  1032. {
  1033. freedom2 = int.Parse( parameterList[2], System.Globalization.CultureInfo.InvariantCulture );
  1034. }
  1035. catch(System.Exception)
  1036. {
  1037. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidDegreeOfFreedom);
  1038. }
  1039. outLabels = null;
  1040. // Output arrays
  1041. outputValues = new double [2][];
  1042. // Output Labels
  1043. outLabels = new string [1][];
  1044. // Parameters description
  1045. outLabels[0] = new string [1];
  1046. // X
  1047. outputValues[0] = new double [1];
  1048. // Y
  1049. outputValues[1] = new double [1];
  1050. outLabels[0][0] = SR.LabelStatisticalProbability;
  1051. outputValues[0][0] = 1;
  1052. outputValues[1][0] = FDistributionInverse( probability, freedom1, freedom2 );
  1053. }
  1054. /// <summary>
  1055. /// Returns the inverse of the standard normal
  1056. /// cumulative distribution. The distribution
  1057. /// has a mean of zero and a standard deviation
  1058. /// of one.
  1059. /// </summary>
  1060. /// <param name="outputValues">Arrays of doubles - Output values</param>
  1061. /// <param name="parameterList">Array of strings - Parameters</param>
  1062. /// <param name="outLabels">Array of strings - Used for Labels. Description for output results.</param>
  1063. private void NormalDistributionInverse(out double [][] outputValues, string [] parameterList, out string [][] outLabels )
  1064. {
  1065. // Alpha value value
  1066. double alpha;
  1067. try
  1068. {
  1069. alpha = double.Parse( parameterList[0], System.Globalization.CultureInfo.InvariantCulture );
  1070. }
  1071. catch(System.Exception)
  1072. {
  1073. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidAlphaValue);
  1074. }
  1075. outLabels = null;
  1076. // Output arrays
  1077. outputValues = new double [2][];
  1078. // Output Labels
  1079. outLabels = new string [1][];
  1080. // Parameters description
  1081. outLabels[0] = new string [1];
  1082. // X
  1083. outputValues[0] = new double [1];
  1084. // Y
  1085. outputValues[1] = new double [1];
  1086. outLabels[0][0] = SR.LabelStatisticalProbability;
  1087. outputValues[0][0] = 1;
  1088. outputValues[1][0] = this.NormalDistributionInverse( alpha );
  1089. }
  1090. #endregion
  1091. #region Utility Statistical Functions
  1092. /// <summary>
  1093. /// Check number of data points. The number should be greater then 1.
  1094. /// </summary>
  1095. /// <param name="inputValues">Input series</param>
  1096. private void CheckNumOfPoints( double [][] inputValues )
  1097. {
  1098. if( inputValues[1].Length < 2 )
  1099. {
  1100. throw new ArgumentException(SR.ExceptionStatisticalAnalysesNotEnoughDataPoints);
  1101. }
  1102. if( inputValues.Length > 2 )
  1103. {
  1104. if( inputValues[2].Length < 2 )
  1105. {
  1106. throw new ArgumentException(SR.ExceptionStatisticalAnalysesNotEnoughDataPoints);
  1107. }
  1108. }
  1109. }
  1110. /// <summary>
  1111. /// Returns covariance, the average of the products of deviations
  1112. /// for each data point pair. Use covariance to determine the
  1113. /// relationship between two data sets. For example, you can
  1114. /// examine whether greater income accompanies greater
  1115. /// levels of education.
  1116. /// </summary>
  1117. /// <param name="arrayX">First data set from X random variable.</param>
  1118. /// <param name="arrayY">Second data set from Y random variable.</param>
  1119. /// <returns>Returns covariance</returns>
  1120. private double Covar( double [] arrayX, double [] arrayY )
  1121. {
  1122. // Check the number of data points
  1123. if( arrayX.Length != arrayY.Length )
  1124. {
  1125. throw new ArgumentException(SR.ExceptionStatisticalAnalysesCovariance);
  1126. }
  1127. double [] arrayXY = new double[arrayX.Length];
  1128. // Find XY
  1129. for( int index = 0; index < arrayX.Length; index++ )
  1130. {
  1131. arrayXY[index] = arrayX[index] * arrayY[index];
  1132. }
  1133. // Find means
  1134. double meanXY = Mean( arrayXY );
  1135. double meanX = Mean( arrayX );
  1136. double meanY = Mean( arrayY );
  1137. // return covariance
  1138. return meanXY - meanX * meanY;
  1139. }
  1140. /// <summary>
  1141. /// Returns the natural logarithm of the gamma function, G(x).
  1142. /// </summary>
  1143. /// <param name="n">The value for which you want to calculate gamma function.</param>
  1144. /// <returns>Returns the natural logarithm of the gamma function.</returns>
  1145. private double GammLn( double n )
  1146. {
  1147. double x;
  1148. double y;
  1149. double tmp;
  1150. double sum;
  1151. double [] cof = {76.18009172947146, -86.50532032941677, 24.01409824083091, -1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5};
  1152. if( n < 0 )
  1153. {
  1154. throw new ArgumentOutOfRangeException(SR.ExceptionStatisticalAnalysesGammaBetaNegativeParameters);
  1155. }
  1156. // Iterative method for Gamma function
  1157. y = x = n;
  1158. tmp = x + 5.5;
  1159. tmp -= ( x + 0.5 ) * Math.Log( tmp );
  1160. sum = 1.000000000190015;
  1161. for( int item = 0; item <=5; item++ )
  1162. {
  1163. sum += cof[item] / ++y;
  1164. }
  1165. return -tmp + Math.Log( 2.5066282746310005 * sum / x );
  1166. }
  1167. /// <summary>
  1168. /// Calculates Beta function
  1169. /// </summary>
  1170. /// <param name="m">First parameter for beta function</param>
  1171. /// <param name="n">Second parameter for beta function</param>
  1172. /// <returns>returns beta function</returns>
  1173. private double BetaFunction( double m, double n )
  1174. {
  1175. return Math.Exp( GammLn( m ) + GammLn( n ) - GammLn( m + n ) );
  1176. }
  1177. /// <summary>
  1178. /// Used by betai: Evaluates continued fraction for
  1179. /// incomplete beta function by modified Lentz’s
  1180. /// </summary>
  1181. /// <param name="a">Beta incomplete parameter</param>
  1182. /// <param name="b">Beta incomplete parameter</param>
  1183. /// <param name="x">Beta incomplete parameter</param>
  1184. /// <returns>Value used for Beta incomplete function</returns>
  1185. private double BetaCF( double a, double b, double x )
  1186. {
  1187. int MAXIT = 100;
  1188. double EPS = 3.0e-7;
  1189. double FPMIN = 1.0e-30;
  1190. int m,m2;
  1191. double aa,c,d,del,h,qab,qam,qap;
  1192. qab = a + b;
  1193. qap= a + 1.0;
  1194. qam = a - 1.0;
  1195. c = 1.0;
  1196. d = 1.0 - qab * x / qap;
  1197. if ( Math.Abs(d) < FPMIN ) d=FPMIN;
  1198. d = 1.0 / d;
  1199. h = d;
  1200. // Numerical approximation for Beta incomplete function
  1201. for( m=1; m<=MAXIT; m++ )
  1202. {
  1203. m2 = 2*m;
  1204. aa = m*(b-m)*x/((qam+m2)*(a+m2));
  1205. // Find d coeficient
  1206. d = 1.0 + aa*d;
  1207. if( Math.Abs(d) < FPMIN ) d=FPMIN;
  1208. // Find c coeficient
  1209. c = 1.0 + aa / c;
  1210. if( Math.Abs(c) < FPMIN ) c = FPMIN;
  1211. // Find d coeficient
  1212. d = 1.0 / d;
  1213. // Find h coeficient
  1214. h *= d*c;
  1215. aa = -(a+m)*(qab+m)*x/((a+m2)*(qap+m2));
  1216. // Recalc d coeficient
  1217. d=1.0+aa*d;
  1218. if (Math.Abs(d) < FPMIN) d=FPMIN;
  1219. // Recalc c coeficient
  1220. c=1.0+aa/c;
  1221. if (Math.Abs(c) < FPMIN) c=FPMIN;
  1222. // Recalc d coeficient
  1223. d=1.0/d;
  1224. del=d*c;
  1225. // Recalc h coeficient
  1226. h *= del;
  1227. if (Math.Abs(del-1.0) < EPS)
  1228. {
  1229. break;
  1230. }
  1231. }
  1232. if (m > MAXIT)
  1233. {
  1234. throw new InvalidOperationException(SR.ExceptionStatisticalAnalysesIncompleteBetaFunction);
  1235. }
  1236. return h;
  1237. }
  1238. /// <summary>
  1239. /// Standard normal density function
  1240. /// </summary>
  1241. /// <param name="t">T Value</param>
  1242. /// <returns>Standard normal density</returns>
  1243. private double NormalDistributionFunction(double t)
  1244. {
  1245. return 0.398942280401433 * Math.Exp( -t * t / 2 );
  1246. }
  1247. /// <summary>
  1248. /// Returns the incomplete beta function Ix(a, b).
  1249. /// </summary>
  1250. /// <param name="a">Beta incomplete parameter</param>
  1251. /// <param name="b">Beta incomplete parameter</param>
  1252. /// <param name="x">Beta incomplete parameter</param>
  1253. /// <returns>Beta Incomplete value</returns>
  1254. private double BetaIncomplete( double a, double b, double x )
  1255. {
  1256. double bt;
  1257. if (x < 0.0 || x > 1.0)
  1258. throw new ArgumentOutOfRangeException(SR.ExceptionStatisticalAnalysesInvalidInputParameter);
  1259. if (x == 0.0 || x == 1.0)
  1260. {
  1261. bt = 0.0;
  1262. }
  1263. else
  1264. { // Factors in front of the continued fraction.
  1265. bt = Math.Exp(GammLn(a + b) - GammLn(a) - GammLn(b) + a * Math.Log(x) + b * Math.Log(1.0 - x));
  1266. }
  1267. if (x < (a + 1.0) / (a + b + 2.0))
  1268. { //Use continued fraction directly.
  1269. return bt * BetaCF(a, b, x) / a;
  1270. }
  1271. else
  1272. { // Use continued fraction after making the symmetry transformation.
  1273. return 1.0 - bt * BetaCF(b, a, 1.0 - x) / b;
  1274. }
  1275. }
  1276. #endregion // Utility Statistical Functions
  1277. #region Statistical Parameters
  1278. /// <summary>
  1279. /// Returns the average (arithmetic mean) of the arguments.
  1280. /// </summary>
  1281. /// <param name="inputValues">Arrays of doubles - Input values</param>
  1282. /// <param name="outputValues">Arrays of doubles - Output values</param>
  1283. /// <param name="outLabels">Array of strings - Used for Labels. Description for output results.</param>
  1284. private void Average(double [][] inputValues, out double [][] outputValues, out string [][] outLabels )
  1285. {
  1286. outLabels = null;
  1287. // Invalid number of data series
  1288. if( inputValues.Length != 2 )
  1289. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidSeriesNumber);
  1290. // Output arrays
  1291. outputValues = new double [2][];
  1292. // Output Labels
  1293. outLabels = new string [1][];
  1294. // Parameters description
  1295. outLabels[0] = new string [1];
  1296. // X
  1297. outputValues[0] = new double [1];
  1298. // Y
  1299. outputValues[1] = new double [1];
  1300. outLabels[0][0] = SR.LabelStatisticalAverage;
  1301. outputValues[0][0] = 1;
  1302. outputValues[1][0] = Mean( inputValues[1] );
  1303. }
  1304. /// <summary>
  1305. /// Calculates variance
  1306. /// </summary>
  1307. /// <param name="inputValues">Arrays of doubles - Input values</param>
  1308. /// <param name="outputValues">Arrays of doubles - Output values</param>
  1309. /// <param name="parameterList">Array of strings - Parameters</param>
  1310. /// <param name="outLabels">Array of strings - Used for Labels. Description for output results.</param>
  1311. private void Variance(double [][] inputValues, out double [][] outputValues, string [] parameterList, out string [][] outLabels )
  1312. {
  1313. // Sample Variance value
  1314. bool sampleVariance;
  1315. try
  1316. {
  1317. sampleVariance = bool.Parse( parameterList[0] );
  1318. }
  1319. catch(System.Exception)
  1320. {
  1321. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidVariance);
  1322. }
  1323. CheckNumOfPoints(inputValues);
  1324. // Invalid number of data series
  1325. if( inputValues.Length != 2 )
  1326. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidSeriesNumber);
  1327. outLabels = null;
  1328. // Output arrays
  1329. outputValues = new double [2][];
  1330. // Output Labels
  1331. outLabels = new string [1][];
  1332. // Parameters description
  1333. outLabels[0] = new string [1];
  1334. // X
  1335. outputValues[0] = new double [1];
  1336. // Y
  1337. outputValues[1] = new double [1];
  1338. outLabels[0][0] = SR.LabelStatisticalVariance;
  1339. outputValues[0][0] = 1;
  1340. outputValues[1][0] = Variance( inputValues[1], sampleVariance );
  1341. }
  1342. /// <summary>
  1343. /// Calculates Median
  1344. /// </summary>
  1345. /// <param name="inputValues">Arrays of doubles - Input values</param>
  1346. /// <param name="outputValues">Arrays of doubles - Output values</param>
  1347. /// <param name="outLabels">Array of strings - Used for Labels. Description for output results.</param>
  1348. private void Median(double [][] inputValues, out double [][] outputValues, out string [][] outLabels )
  1349. {
  1350. outLabels = null;
  1351. // Invalid number of data series
  1352. if( inputValues.Length != 2 )
  1353. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidSeriesNumber);
  1354. // Output arrays
  1355. outputValues = new double [2][];
  1356. // Output Labels
  1357. outLabels = new string [1][];
  1358. // Parameters description
  1359. outLabels[0] = new string [1];
  1360. // X
  1361. outputValues[0] = new double [1];
  1362. // Y
  1363. outputValues[1] = new double [1];
  1364. outLabels[0][0] = SR.LabelStatisticalMedian;
  1365. outputValues[0][0] = 1;
  1366. outputValues[1][0] = Median( inputValues[1] );
  1367. }
  1368. /// <summary>
  1369. /// Calculates Beta Function
  1370. /// </summary>
  1371. /// <param name="outputValues">Arrays of doubles - Output values</param>
  1372. /// <param name="parameterList">Array of strings - Parameters</param>
  1373. /// <param name="outLabels">Array of strings - Used for Labels. Description for output results.</param>
  1374. private void BetaFunction(out double [][] outputValues, string [] parameterList, out string [][] outLabels )
  1375. {
  1376. // Degree of freedom
  1377. double m;
  1378. try
  1379. {
  1380. m = double.Parse( parameterList[0], System.Globalization.CultureInfo.InvariantCulture );
  1381. }
  1382. catch(System.Exception)
  1383. {
  1384. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidDegreeOfFreedom);
  1385. }
  1386. // Degree of freedom
  1387. double n;
  1388. try
  1389. {
  1390. n = double.Parse( parameterList[1], System.Globalization.CultureInfo.InvariantCulture );
  1391. }
  1392. catch(System.Exception)
  1393. {
  1394. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidDegreeOfFreedom);
  1395. }
  1396. outLabels = null;
  1397. // Output arrays
  1398. outputValues = new double [2][];
  1399. // Output Labels
  1400. outLabels = new string [1][];
  1401. // Parameters description
  1402. outLabels[0] = new string [1];
  1403. // X
  1404. outputValues[0] = new double [1];
  1405. // Y
  1406. outputValues[1] = new double [1];
  1407. outLabels[0][0] = SR.LabelStatisticalBetaFunction;
  1408. outputValues[0][0] = 1;
  1409. outputValues[1][0] = BetaFunction( m, n );
  1410. }
  1411. /// <summary>
  1412. /// Calculates Gamma Function
  1413. /// </summary>
  1414. /// <param name="outputValues">Arrays of doubles - Output values</param>
  1415. /// <param name="parameterList">Array of strings - Parameters</param>
  1416. /// <param name="outLabels">Array of strings - Used for Labels. Description for output results.</param>
  1417. private void GammaFunction(out double [][] outputValues, string [] parameterList, out string [][] outLabels )
  1418. {
  1419. // Degree of freedom
  1420. double m;
  1421. try
  1422. {
  1423. m = double.Parse( parameterList[0], System.Globalization.CultureInfo.InvariantCulture );
  1424. }
  1425. catch(System.Exception)
  1426. {
  1427. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidInputParameter);
  1428. }
  1429. if( m < 0 )
  1430. {
  1431. throw new ArgumentOutOfRangeException(SR.ExceptionStatisticalAnalysesGammaBetaNegativeParameters);
  1432. }
  1433. outLabels = null;
  1434. // Output arrays
  1435. outputValues = new double [2][];
  1436. // Output Labels
  1437. outLabels = new string [1][];
  1438. // Parameters description
  1439. outLabels[0] = new string [1];
  1440. // X
  1441. outputValues[0] = new double [1];
  1442. // Y
  1443. outputValues[1] = new double [1];
  1444. outLabels[0][0] = SR.LabelStatisticalGammaFunction;
  1445. outputValues[0][0] = 1;
  1446. outputValues[1][0] = Math.Exp( GammLn( m ) );
  1447. }
  1448. /// <summary>
  1449. /// Sort array of double values.
  1450. /// </summary>
  1451. /// <param name="values">Array of doubles which should be sorted.</param>
  1452. private void Sort( ref double [] values )
  1453. {
  1454. double tempValue;
  1455. for( int outLoop = 0; outLoop < values.Length; outLoop++ )
  1456. {
  1457. for( int inLoop = outLoop + 1; inLoop < values.Length; inLoop++ )
  1458. {
  1459. if( values[ outLoop ] > values[ inLoop ] )
  1460. {
  1461. tempValue = values[ outLoop ];
  1462. values[ outLoop ] = values[ inLoop ];
  1463. values[ inLoop ] = tempValue;
  1464. }
  1465. }
  1466. }
  1467. }
  1468. /// <summary>
  1469. /// Returns the median of the given numbers
  1470. /// </summary>
  1471. /// <param name="values">Array of double numbers</param>
  1472. /// <returns>Median</returns>
  1473. private double Median( double [] values )
  1474. {
  1475. // Exception for zero lenght of series.
  1476. if( values.Length == 0 )
  1477. {
  1478. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidMedianConditions);
  1479. }
  1480. // Sort array
  1481. Sort( ref values );
  1482. int position = values.Length / 2;
  1483. // if number of points is even
  1484. if( values.Length % 2 == 0 )
  1485. {
  1486. return ( values[position-1] + values[position] ) / 2.0;
  1487. }
  1488. else
  1489. {
  1490. return values[position];
  1491. }
  1492. }
  1493. /// <summary>
  1494. /// Calculates a Mean for a series of numbers.
  1495. /// </summary>
  1496. /// <param name="values">series with double numbers</param>
  1497. /// <returns>Returns Mean</returns>
  1498. private double Mean( double [] values )
  1499. {
  1500. // Exception for zero lenght of series.
  1501. if( values.Length == 0 )
  1502. {
  1503. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidMeanConditions);
  1504. }
  1505. // Find sum of values
  1506. double sum = 0;
  1507. foreach( double item in values )
  1508. {
  1509. sum += item;
  1510. }
  1511. // Calculate Mean
  1512. return sum / values.Length;
  1513. }
  1514. /// <summary>
  1515. /// Calculates a Variance for a series of numbers.
  1516. /// </summary>
  1517. /// <param name="values">double values</param>
  1518. /// <param name="sampleVariance">If variance is calculated from sample sum has to be divided by n-1.</param>
  1519. /// <returns>Variance</returns>
  1520. private double Variance( double [] values, bool sampleVariance )
  1521. {
  1522. // Exception for zero lenght of series.
  1523. if( values.Length < 1 )
  1524. {
  1525. throw new ArgumentException(SR.ExceptionStatisticalAnalysesInvalidVarianceConditions);
  1526. }
  1527. // Find sum of values
  1528. double sum = 0;
  1529. double mean = Mean( values );
  1530. foreach( double item in values )
  1531. {
  1532. sum += (item - mean) * (item - mean);
  1533. }
  1534. // Calculate Variance
  1535. if( sampleVariance )
  1536. {
  1537. return sum / ( values.Length - 1 );
  1538. }
  1539. else
  1540. {
  1541. return sum / values.Length;
  1542. }
  1543. }
  1544. #endregion // Statistical Parameters
  1545. # region Distributions
  1546. /// <summary>
  1547. /// Calculates the Percentage Points (probability) for the Student
  1548. /// t-distribution. The t-distribution is used in the hypothesis
  1549. /// testing of small sample data sets. Use this function in place
  1550. /// of a table of critical values for the t-distribution.
  1551. /// </summary>
  1552. /// <param name="tValue">The numeric value at which to evaluate the distribution.</param>
  1553. /// <param name="n">An integer indicating the number of degrees of freedom.</param>
  1554. /// <param name="oneTailed">Specifies the number of distribution tails to return.</param>
  1555. /// <returns>Returns the Percentage Points (probability) for the Student t-distribution.</returns>
  1556. private double StudentsDistribution( double tValue, int n, bool oneTailed )
  1557. {
  1558. // Validation
  1559. tValue = Math.Abs( tValue );
  1560. if( n > 300 )
  1561. {
  1562. n = 300;
  1563. }
  1564. if( n < 1 )
  1565. {
  1566. throw new ArgumentOutOfRangeException(SR.ExceptionStatisticalAnalysesStudentsNegativeFreedomDegree);
  1567. }
  1568. double result = 1 - BetaIncomplete( n / 2.0, 0.5, n / (n + tValue * tValue) );
  1569. if( oneTailed )
  1570. return ( 1.0 - result ) / 2.0;
  1571. else
  1572. return 1.0 - result;
  1573. }
  1574. /// <summary>
  1575. /// Returns the standard normal cumulative distribution
  1576. /// function. The distribution has a mean of 0 (zero) and
  1577. /// a standard deviation of one. Use this function in place
  1578. /// of a table of standard normal curve areas.
  1579. /// </summary>
  1580. /// <param name="zValue">The value for which you want the distribution.</param>
  1581. /// <returns>Returns the standard normal cumulative distribution.</returns>
  1582. private double NormalDistribution( double zValue )
  1583. {
  1584. double [] a = {0.31938153,-0.356563782,1.781477937,-1.821255978,1.330274429};
  1585. double result;
  1586. if (zValue<-7.0)
  1587. {
  1588. result = NormalDistributionFunction(zValue)/Math.Sqrt(1.0+zValue*zValue);
  1589. }
  1590. else if (zValue>7.0)
  1591. {
  1592. result = 1.0 - NormalDistribution(-zValue);
  1593. }
  1594. else
  1595. {
  1596. result = 0.2316419;
  1597. result=1.0/(1+result*Math.Abs(zValue));
  1598. result=1-NormalDistributionFunction(zValue)*(result*(a[0]+result*(a[1]+result*(a[2]+result*(a[3]+result*a[4])))));
  1599. if (zValue<=0.0)
  1600. result=1.0-result;
  1601. }
  1602. return result;
  1603. }
  1604. private double FDistribution( double x, int freedom1, int freedom2 )
  1605. {
  1606. if (x < 0)
  1607. throw new ArgumentOutOfRangeException(SR.ExceptionStatisticalAnalysesInvalidTValue);
  1608. if (freedom1 <= 0)
  1609. throw new ArgumentOutOfRangeException(SR.ExceptionStatisticalAnalysesInvalidDegreeOfFreedom);
  1610. if (freedom2 <= 0)
  1611. throw new ArgumentOutOfRangeException(SR.ExceptionStatisticalAnalysesInvalidDegreeOfFreedom);
  1612. if (x == 0)
  1613. return 1;
  1614. if (x == double.PositiveInfinity)
  1615. return 0;
  1616. return BetaIncomplete( freedom2 / 2.0, freedom1 / 2.0, freedom2 / ( freedom2 + freedom1 * x ) );
  1617. }
  1618. #endregion // Distributions
  1619. # region Inverse Distributions
  1620. /// <summary>
  1621. /// Calculates the t-value of the Student's t-distribution
  1622. /// as a function of the probability and the degrees of freedom.
  1623. /// </summary>
  1624. /// <param name="probability">The probability associated with the two-tailed Student's t-distribution.</param>
  1625. /// <param name="n">The number of degrees of freedom to characterize the distribution.</param>
  1626. /// <returns>Returns the t-value of the Student's t-distribution.</returns>
  1627. private double StudentsDistributionInverse( double probability, int n )
  1628. {
  1629. //Fix for boundary cases
  1630. if (probability == 0)
  1631. return double.PositiveInfinity;
  1632. else if (probability == 1)
  1633. return 0;
  1634. else if (probability < 0 || probability > 1)
  1635. throw new ArgumentOutOfRangeException(SR.ExceptionStatisticalAnalysesInvalidProbabilityValue);
  1636. int step = 0;
  1637. return StudentsDistributionSearch( probability, n, step, 0.0, 100000.0 );
  1638. }
  1639. /// <summary>
  1640. /// Method for calculation of Inverse T Distribution (Binary tree)
  1641. /// solution for non linear equations
  1642. /// </summary>
  1643. /// <param name="probability">Probability value</param>
  1644. /// <param name="n">Degree of freedom</param>
  1645. /// <param name="step">Step for Numerical solution for non linear equations</param>
  1646. /// <param name="start">Start for numerical process</param>
  1647. /// <param name="end">End for numerical process</param>
  1648. /// <returns>Returns F ditribution inverse</returns>
  1649. private double StudentsDistributionSearch( double probability, int n, int step, double start, double end )
  1650. {
  1651. step++;
  1652. double mid = ( start + end ) / 2.0;
  1653. double result = StudentsDistribution( mid, n, false );
  1654. double resultX;
  1655. if( step > 100 )
  1656. {
  1657. return mid;
  1658. }
  1659. if( result <= probability )
  1660. {
  1661. resultX = StudentsDistributionSearch( probability, n, step, start, mid );
  1662. }
  1663. else
  1664. {
  1665. resultX = StudentsDistributionSearch( probability, n, step, mid, end );
  1666. }
  1667. return resultX;
  1668. }
  1669. /// <summary>
  1670. /// Returns the inverse of the standard normal cumulative distribution.
  1671. /// The distribution has a mean of zero and a standard deviation of one.
  1672. /// </summary>
  1673. /// <param name="probability">A probability corresponding to the normal distribution.</param>
  1674. /// <returns>Returns the inverse of the standard normal cumulative distribution.</returns>
  1675. private double NormalDistributionInverse( double probability )
  1676. {
  1677. // Validation
  1678. if( probability < 0.00001 || probability > 0.99999 )
  1679. {
  1680. throw new ArgumentOutOfRangeException(SR.ExceptionStatisticalAnalysesNormalInvalidProbabilityValue);
  1681. }
  1682. double [] a = { 2.50662823884, -18.61500062529, 41.39119773534, -25.44106049637 };
  1683. double [] b = { -8.47351093090, 23.08336743743, -21.06224101826, 3.13082909833 };
  1684. double [] c = { 0.3374754822726147, 0.9761690190917186, 0.1607979714918209, 0.0276438810333863, 0.0038405729373609, 0.0003951896511919, 0.0000321767881768, 0.0000002888167364, 0.0000003960315187};
  1685. double x,r;
  1686. // Numerical Integration
  1687. x = probability - 0.5;
  1688. if ( Math.Abs(x) < 0.42 )
  1689. {
  1690. r = x * x;
  1691. r = x * ( ( ( a[3] * r + a[2] ) * r + a[1] ) * r + a[0] ) / ( ( ( ( b[3] * r + b[2] ) * r + b[1] ) * r + b[0] ) * r + 1.0 );
  1692. return( r );
  1693. }
  1694. r= probability;
  1695. if( x > 0.0 )
  1696. {
  1697. r = 1.0 - probability;
  1698. }
  1699. r = Math.Log( -Math.Log( r ) );
  1700. r = c[0] + r * ( c[1] + r * ( c[2] + r * ( c[3] + r * ( c[4] + r * ( c[5] + r * ( c[6] + r * ( c[7]+r * c[8] ) ) ) ) ) ) );
  1701. if( x < 0.0 )
  1702. {
  1703. r = -r;
  1704. }
  1705. return r;
  1706. }
  1707. /// <summary>
  1708. /// Calculates the inverse of the F probability distribution.
  1709. /// The F distribution can be used in an F-test that compares
  1710. /// the degree of variability in two data sets.
  1711. /// </summary>
  1712. /// <param name="probability">A probability associated with the F cumulative distribution.</param>
  1713. /// <param name="m">The numerator degrees of freedom.</param>
  1714. /// <param name="n">The denominator degrees of freedom.</param>
  1715. /// <returns>Returns the inverse of the F probability distribution.</returns>
  1716. private double FDistributionInverse( double probability, int m, int n )
  1717. {
  1718. //Fix for boundary cases
  1719. if (probability == 0)
  1720. return double.PositiveInfinity;
  1721. else if (probability == 1)
  1722. return 0;
  1723. else if (probability < 0 || probability > 1)
  1724. throw new ArgumentOutOfRangeException(SR.ExceptionStatisticalAnalysesInvalidProbabilityValue);
  1725. int step = 0;
  1726. return FDistributionSearch( probability, m, n, step, 0.0, 10000.0 );
  1727. }
  1728. /// <summary>
  1729. /// Method for calculation of Inverse F Distribution (Binary tree)
  1730. /// solution for non linear equations
  1731. /// </summary>
  1732. /// <param name="probability">Probability value</param>
  1733. /// <param name="m">Degree of freedom</param>
  1734. /// <param name="n">Degree of freedom</param>
  1735. /// <param name="step">Step for solution for non linear equations.</param>
  1736. /// <param name="start">Start for numerical process</param>
  1737. /// <param name="end">End for numerical process</param>
  1738. /// <returns>Returns F ditribution inverse</returns>
  1739. private double FDistributionSearch( double probability, int m, int n, int step, double start, double end )
  1740. {
  1741. step++;
  1742. double mid = ( start + end ) / 2.0;
  1743. double result = FDistribution( mid, m, n );
  1744. double resultX;
  1745. if( step > 30 )
  1746. {
  1747. return mid;
  1748. }
  1749. if( result <= probability )
  1750. {
  1751. resultX = FDistributionSearch( probability, m, n, step, start, mid );
  1752. }
  1753. else
  1754. {
  1755. resultX = FDistributionSearch( probability, m, n, step, mid, end );
  1756. }
  1757. return resultX;
  1758. }
  1759. #endregion // Inverse Distributions
  1760. }
  1761. }