math.pp 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 1999-2005 by Florian Klaempfl
  4. member of the Free Pascal development team
  5. See the file COPYING.FPC, included in this distribution,
  6. for details about the copyright.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10. **********************************************************************}
  11. {-------------------------------------------------------------------------
  12. Using functions from AMath/DAMath libraries, which are covered by the
  13. following license:
  14. (C) Copyright 2009-2013 Wolfgang Ehrhardt
  15. This software is provided 'as-is', without any express or implied warranty.
  16. In no event will the authors be held liable for any damages arising from
  17. the use of this software.
  18. Permission is granted to anyone to use this software for any purpose,
  19. including commercial applications, and to alter it and redistribute it
  20. freely, subject to the following restrictions:
  21. 1. The origin of this software must not be misrepresented; you must not
  22. claim that you wrote the original software. If you use this software in
  23. a product, an acknowledgment in the product documentation would be
  24. appreciated but is not required.
  25. 2. Altered source versions must be plainly marked as such, and must not be
  26. misrepresented as being the original software.
  27. 3. This notice may not be removed or altered from any source distribution.
  28. ----------------------------------------------------------------------------}
  29. {
  30. This unit is an equivalent to the Delphi Math unit
  31. (with some improvements)
  32. What's to do:
  33. o some statistical functions
  34. o optimizations
  35. }
  36. {$MODE objfpc}
  37. {$inline on }
  38. {$GOTO on}
  39. unit Math;
  40. interface
  41. {$ifndef FPUNONE}
  42. uses
  43. sysutils;
  44. {$IFDEF FPDOC_MATH}
  45. Type
  46. Float = MaxFloatType;
  47. Const
  48. MinFloat = 0;
  49. MaxFloat = 0;
  50. {$ENDIF}
  51. { Ranges of the IEEE floating point types, including denormals }
  52. {$ifdef FPC_HAS_TYPE_SINGLE}
  53. const
  54. { values according to
  55. https://en.wikipedia.org/wiki/Single-precision_floating-point_format#Single-precision_examples
  56. }
  57. MinSingle = 1.1754943508e-38;
  58. MaxSingle = 3.4028234664e+38;
  59. {$endif FPC_HAS_TYPE_SINGLE}
  60. {$ifdef FPC_HAS_TYPE_DOUBLE}
  61. const
  62. { values according to
  63. https://en.wikipedia.org/wiki/Double-precision_floating-point_format#Double-precision_examples
  64. }
  65. MinDouble = 2.2250738585072014e-308;
  66. MaxDouble = 1.7976931348623157e+308;
  67. {$endif FPC_HAS_TYPE_DOUBLE}
  68. {$ifdef FPC_HAS_TYPE_EXTENDED}
  69. const
  70. MinExtended = 3.4e-4932;
  71. MaxExtended = 1.1e+4932;
  72. {$endif FPC_HAS_TYPE_EXTENDED}
  73. {$ifdef FPC_HAS_TYPE_COMP}
  74. const
  75. MinComp = -9.223372036854775807e+18;
  76. MaxComp = 9.223372036854775807e+18;
  77. {$endif FPC_HAS_TYPE_COMP}
  78. { the original delphi functions use extended as argument, }
  79. { but I would prefer double, because 8 bytes is a very }
  80. { natural size for the processor }
  81. { WARNING : changing float type will }
  82. { break all assembler code PM }
  83. {$if defined(FPC_HAS_TYPE_FLOAT128)}
  84. type
  85. Float = Float128;
  86. const
  87. MinFloat = MinFloat128;
  88. MaxFloat = MaxFloat128;
  89. {$elseif defined(FPC_HAS_TYPE_EXTENDED)}
  90. type
  91. Float = extended;
  92. const
  93. MinFloat = MinExtended;
  94. MaxFloat = MaxExtended;
  95. {$elseif defined(FPC_HAS_TYPE_DOUBLE)}
  96. type
  97. Float = double;
  98. const
  99. MinFloat = MinDouble;
  100. MaxFloat = MaxDouble;
  101. {$elseif defined(FPC_HAS_TYPE_SINGLE)}
  102. type
  103. Float = single;
  104. const
  105. MinFloat = MinSingle;
  106. MaxFloat = MaxSingle;
  107. {$else}
  108. {$fatal At least one floating point type must be supported}
  109. {$endif}
  110. type
  111. PFloat = ^Float;
  112. PInteger = ObjPas.PInteger;
  113. TPaymentTime = (ptEndOfPeriod,ptStartOfPeriod);
  114. EInvalidArgument = class(ematherror);
  115. TValueRelationship = -1..1;
  116. const
  117. EqualsValue = 0;
  118. LessThanValue = Low(TValueRelationship);
  119. GreaterThanValue = High(TValueRelationship);
  120. {$push}
  121. {$R-}
  122. {$Q-}
  123. NaN = 0.0/0.0;
  124. Infinity = 1.0/0.0;
  125. NegInfinity = -1.0/0.0;
  126. {$pop}
  127. {$IFDEF FPDOC_MATH}
  128. // This must be after the above defines.
  129. {$DEFINE FPC_HAS_TYPE_SINGLE}
  130. {$DEFINE FPC_HAS_TYPE_DOUBLE}
  131. {$DEFINE FPC_HAS_TYPE_EXTENDED}
  132. {$DEFINE FPC_HAS_TYPE_COMP}
  133. {$ENDIF}
  134. { Min/max determination }
  135. function MinIntValue(const Data: array of Integer): Integer;
  136. function MaxIntValue(const Data: array of Integer): Integer;
  137. { Extra, not present in Delphi, but used frequently }
  138. function Min(a, b: Integer): Integer;inline; overload;
  139. function Max(a, b: Integer): Integer;inline; overload;
  140. { this causes more trouble than it solves
  141. function Min(a, b: Cardinal): Cardinal; overload;
  142. function Max(a, b: Cardinal): Cardinal; overload;
  143. }
  144. function Min(a, b: Int64): Int64;inline; overload;
  145. function Max(a, b: Int64): Int64;inline; overload;
  146. function Min(a, b: QWord): QWord;inline; overload;
  147. function Max(a, b: QWord): QWord;inline; overload;
  148. {$ifdef FPC_HAS_TYPE_SINGLE}
  149. function Min(a, b: Single): Single;inline; overload;
  150. function Max(a, b: Single): Single;inline; overload;
  151. {$endif FPC_HAS_TYPE_SINGLE}
  152. {$ifdef FPC_HAS_TYPE_DOUBLE}
  153. function Min(a, b: Double): Double;inline; overload;
  154. function Max(a, b: Double): Double;inline; overload;
  155. {$endif FPC_HAS_TYPE_DOUBLE}
  156. {$ifdef FPC_HAS_TYPE_EXTENDED}
  157. function Min(a, b: Extended): Extended;inline; overload;
  158. function Max(a, b: Extended): Extended;inline; overload;
  159. {$endif FPC_HAS_TYPE_EXTENDED}
  160. function InRange(const AValue, AMin, AMax: Integer): Boolean;inline; overload;
  161. function InRange(const AValue, AMin, AMax: Int64): Boolean;inline; overload;
  162. {$ifdef FPC_HAS_TYPE_DOUBLE}
  163. function InRange(const AValue, AMin, AMax: Double): Boolean;inline; overload;
  164. {$endif FPC_HAS_TYPE_DOUBLE}
  165. function EnsureRange(const AValue, AMin, AMax: Integer): Integer;inline; overload;
  166. function EnsureRange(const AValue, AMin, AMax: Int64): Int64;inline; overload;
  167. {$ifdef FPC_HAS_TYPE_DOUBLE}
  168. function EnsureRange(const AValue, AMin, AMax: Double): Double;inline; overload;
  169. {$endif FPC_HAS_TYPE_DOUBLE}
  170. procedure DivMod(Dividend: LongInt; Divisor: Word; var Result, Remainder: Word);
  171. procedure DivMod(Dividend: LongInt; Divisor: Word; var Result, Remainder: SmallInt);
  172. procedure DivMod(Dividend: DWord; Divisor: DWord; var Result, Remainder: DWord);
  173. procedure DivMod(Dividend: LongInt; Divisor: LongInt; var Result, Remainder: LongInt);
  174. { Floating point modulo}
  175. {$ifdef FPC_HAS_TYPE_SINGLE}
  176. function FMod(const a, b: Single): Single;inline;overload;
  177. {$endif FPC_HAS_TYPE_SINGLE}
  178. {$ifdef FPC_HAS_TYPE_DOUBLE}
  179. function FMod(const a, b: Double): Double;inline;overload;
  180. {$endif FPC_HAS_TYPE_DOUBLE}
  181. {$ifdef FPC_HAS_TYPE_EXTENDED}
  182. function FMod(const a, b: Extended): Extended;inline;overload;
  183. {$endif FPC_HAS_TYPE_EXTENDED}
  184. operator mod(const a,b:float) c:float;inline;
  185. // Sign functions
  186. Type
  187. TValueSign = -1..1;
  188. const
  189. NegativeValue = Low(TValueSign);
  190. ZeroValue = 0;
  191. PositiveValue = High(TValueSign);
  192. function Sign(const AValue: Integer): TValueSign;inline; overload;
  193. function Sign(const AValue: Int64): TValueSign;inline; overload;
  194. {$ifdef FPC_HAS_TYPE_SINGLE}
  195. function Sign(const AValue: Single): TValueSign;inline; overload;
  196. {$endif}
  197. function Sign(const AValue: Double): TValueSign;inline; overload;
  198. {$ifdef FPC_HAS_TYPE_EXTENDED}
  199. function Sign(const AValue: Extended): TValueSign;inline; overload;
  200. {$endif}
  201. function IsZero(const A: Single; Epsilon: Single): Boolean; overload;
  202. function IsZero(const A: Single): Boolean;inline; overload;
  203. {$ifdef FPC_HAS_TYPE_DOUBLE}
  204. function IsZero(const A: Double; Epsilon: Double): Boolean; overload;
  205. function IsZero(const A: Double): Boolean;inline; overload;
  206. {$endif FPC_HAS_TYPE_DOUBLE}
  207. {$ifdef FPC_HAS_TYPE_EXTENDED}
  208. function IsZero(const A: Extended; Epsilon: Extended): Boolean; overload;
  209. function IsZero(const A: Extended): Boolean;inline; overload;
  210. {$endif FPC_HAS_TYPE_EXTENDED}
  211. function IsNan(const d : Single): Boolean; overload;
  212. {$ifdef FPC_HAS_TYPE_DOUBLE}
  213. function IsNan(const d : Double): Boolean; overload;
  214. {$endif FPC_HAS_TYPE_DOUBLE}
  215. {$ifdef FPC_HAS_TYPE_EXTENDED}
  216. function IsNan(const d : Extended): Boolean; overload;
  217. {$endif FPC_HAS_TYPE_EXTENDED}
  218. function IsInfinite(const d : Single): Boolean; overload;
  219. {$ifdef FPC_HAS_TYPE_DOUBLE}
  220. function IsInfinite(const d : Double): Boolean; overload;
  221. {$endif FPC_HAS_TYPE_DOUBLE}
  222. {$ifdef FPC_HAS_TYPE_EXTENDED}
  223. function IsInfinite(const d : Extended): Boolean; overload;
  224. {$endif FPC_HAS_TYPE_EXTENDED}
  225. {$ifdef FPC_HAS_TYPE_EXTENDED}
  226. function SameValue(const A, B: Extended): Boolean;inline; overload;
  227. {$endif}
  228. {$ifdef FPC_HAS_TYPE_DOUBLE}
  229. function SameValue(const A, B: Double): Boolean;inline; overload;
  230. {$endif}
  231. function SameValue(const A, B: Single): Boolean;inline; overload;
  232. {$ifdef FPC_HAS_TYPE_EXTENDED}
  233. function SameValue(const A, B: Extended; Epsilon: Extended): Boolean; overload;
  234. {$endif}
  235. {$ifdef FPC_HAS_TYPE_DOUBLE}
  236. function SameValue(const A, B: Double; Epsilon: Double): Boolean; overload;
  237. {$endif}
  238. function SameValue(const A, B: Single; Epsilon: Single): Boolean; overload;
  239. type
  240. TRoundToRange = -37..37;
  241. {$ifdef FPC_HAS_TYPE_DOUBLE}
  242. function RoundTo(const AValue: Double; const Digits: TRoundToRange): Double;
  243. {$endif}
  244. {$ifdef FPC_HAS_TYPE_EXTENDED}
  245. function RoundTo(const AVAlue: Extended; const Digits: TRoundToRange): Extended;
  246. {$endif}
  247. {$ifdef FPC_HAS_TYPE_SINGLE}
  248. function RoundTo(const AValue: Single; const Digits: TRoundToRange): Single;
  249. {$endif}
  250. {$ifdef FPC_HAS_TYPE_SINGLE}
  251. function SimpleRoundTo(const AValue: Single; const Digits: TRoundToRange = -2): Single;
  252. {$endif}
  253. {$ifdef FPC_HAS_TYPE_DOUBLE}
  254. function SimpleRoundTo(const AValue: Double; const Digits: TRoundToRange = -2): Double;
  255. {$endif}
  256. {$ifdef FPC_HAS_TYPE_EXTENDED}
  257. function SimpleRoundTo(const AValue: Extended; const Digits: TRoundToRange = -2): Extended;
  258. {$endif}
  259. { angle conversion }
  260. function DegToRad(deg : float) : float;inline;
  261. function RadToDeg(rad : float) : float;inline;
  262. function GradToRad(grad : float) : float;inline;
  263. function RadToGrad(rad : float) : float;inline;
  264. function DegToGrad(deg : float) : float;inline;
  265. function GradToDeg(grad : float) : float;inline;
  266. { one cycle are 2*Pi rad }
  267. function CycleToRad(cycle : float) : float;inline;
  268. function RadToCycle(rad : float) : float;inline;
  269. {$ifdef FPC_HAS_TYPE_SINGLE}
  270. Function DegNormalize(deg : single) : single; inline;
  271. {$ENDIF}
  272. {$ifdef FPC_HAS_TYPE_DOUBLE}
  273. Function DegNormalize(deg : double) : double; inline;
  274. {$ENDIF}
  275. {$ifdef FPC_HAS_TYPE_EXTENDED}
  276. Function DegNormalize(deg : extended) : extended; inline;
  277. {$ENDIF}
  278. { trigoniometric functions }
  279. function Tan(x : float) : float;
  280. function Cotan(x : float) : float;
  281. function Cot(x : float) : float; inline;
  282. {$ifdef FPC_HAS_TYPE_SINGLE}
  283. procedure SinCos(theta : single;out sinus,cosinus : single);
  284. {$endif}
  285. {$ifdef FPC_HAS_TYPE_DOUBLE}
  286. procedure SinCos(theta : double;out sinus,cosinus : double);
  287. {$endif}
  288. {$ifdef FPC_HAS_TYPE_EXTENDED}
  289. procedure SinCos(theta : extended;out sinus,cosinus : extended);
  290. {$endif}
  291. function Secant(x : float) : float; inline;
  292. function Cosecant(x : float) : float; inline;
  293. function Sec(x : float) : float; inline;
  294. function Csc(x : float) : float; inline;
  295. { inverse functions }
  296. function ArcCos(x : float) : float;
  297. function ArcSin(x : float) : float;
  298. { calculates arctan(y/x) and returns an angle in the correct quadrant }
  299. function ArcTan2(y,x : float) : float;
  300. { hyperbolic functions }
  301. function CosH(x : float) : float;
  302. function SinH(x : float) : float;
  303. function TanH(x : float) : float;
  304. { area functions }
  305. { delphi names: }
  306. function ArcCosH(x : float) : float;inline;
  307. function ArcSinH(x : float) : float;inline;
  308. function ArcTanH(x : float) : float;inline;
  309. { IMHO the function should be called as follows (FK) }
  310. function ArCosH(x : float) : float;
  311. function ArSinH(x : float) : float;
  312. function ArTanH(x : float) : float;
  313. { triangle functions }
  314. { returns the length of the hypotenuse of a right triangle }
  315. { if x and y are the other sides }
  316. function Hypot(x,y : float) : float;
  317. { logarithm functions }
  318. function Log10(x : float) : float;
  319. function Log2(x : float) : float;
  320. function LogN(n,x : float) : float;
  321. { returns natural logarithm of x+1, accurate for x values near zero }
  322. function LnXP1(x : float) : float;
  323. { exponential functions }
  324. function Power(base,exponent : float) : float;
  325. { base^exponent }
  326. function IntPower(base : float;exponent : longint) : float;
  327. operator ** (bas,expo : float) e: float; inline;
  328. operator ** (bas,expo : int64) i: int64; inline;
  329. { number converting }
  330. { rounds x towards positive infinity }
  331. function Ceil(x : float) : Integer;
  332. function Ceil64(x: float): Int64;
  333. { rounds x towards negative infinity }
  334. function Floor(x : float) : Integer;
  335. function Floor64(x: float): Int64;
  336. { misc. functions }
  337. {$ifdef FPC_HAS_TYPE_SINGLE}
  338. { splits x into mantissa and exponent (to base 2) }
  339. procedure Frexp(X: single; out Mantissa: single; out Exponent: integer);
  340. { returns x*(2^p) }
  341. function Ldexp(X: single; p: Integer) : single;
  342. {$endif}
  343. {$ifdef FPC_HAS_TYPE_DOUBLE}
  344. procedure Frexp(X: double; out Mantissa: double; out Exponent: integer);
  345. function Ldexp(X: double; p: Integer) : double;
  346. {$endif}
  347. {$ifdef FPC_HAS_TYPE_EXTENDED}
  348. procedure Frexp(X: extended; out Mantissa: extended; out Exponent: integer);
  349. function Ldexp(X: extended; p: Integer) : extended;
  350. {$endif}
  351. { statistical functions }
  352. {$ifdef FPC_HAS_TYPE_SINGLE}
  353. function Mean(const data : array of Single) : float;
  354. function Sum(const data : array of Single) : float;inline;
  355. function Mean(const data : PSingle; Const N : longint) : float;
  356. function Sum(const data : PSingle; Const N : Longint) : float;
  357. {$endif FPC_HAS_TYPE_SINGLE}
  358. {$ifdef FPC_HAS_TYPE_DOUBLE}
  359. function Mean(const data : array of double) : float;inline;
  360. function Sum(const data : array of double) : float;inline;
  361. function Mean(const data : PDouble; Const N : longint) : float;
  362. function Sum(const data : PDouble; Const N : Longint) : float;
  363. {$endif FPC_HAS_TYPE_DOUBLE}
  364. {$ifdef FPC_HAS_TYPE_EXTENDED}
  365. function Mean(const data : array of Extended) : float;
  366. function Sum(const data : array of Extended) : float;inline;
  367. function Mean(const data : PExtended; Const N : longint) : float;
  368. function Sum(const data : PExtended; Const N : Longint) : float;
  369. {$endif FPC_HAS_TYPE_EXTENDED}
  370. function SumInt(const data : PInt64;Const N : longint) : Int64;
  371. function SumInt(const data : array of Int64) : Int64;inline;
  372. function Mean(const data : PInt64; const N : Longint):Float;
  373. function Mean(const data: array of Int64):Float;
  374. function SumInt(const data : PInteger; Const N : longint) : Int64;
  375. function SumInt(const data : array of Integer) : Int64;inline;
  376. function Mean(const data : PInteger; const N : Longint):Float;
  377. function Mean(const data: array of Integer):Float;
  378. {$ifdef FPC_HAS_TYPE_SINGLE}
  379. function SumOfSquares(const data : array of Single) : float;inline;
  380. function SumOfSquares(const data : PSingle; Const N : Integer) : float;
  381. { calculates the sum and the sum of squares of data }
  382. procedure SumsAndSquares(const data : array of Single;
  383. var sum,sumofsquares : float);inline;
  384. procedure SumsAndSquares(const data : PSingle; Const N : Integer;
  385. var sum,sumofsquares : float);
  386. {$endif FPC_HAS_TYPE_SINGLE}
  387. {$ifdef FPC_HAS_TYPE_DOUBLE}
  388. function SumOfSquares(const data : array of double) : float;
  389. function SumOfSquares(const data : PDouble; Const N : Integer) : float;
  390. { calculates the sum and the sum of squares of data }
  391. procedure SumsAndSquares(const data : array of Double;
  392. var sum,sumofsquares : float);inline;
  393. procedure SumsAndSquares(const data : PDouble; Const N : Integer;
  394. var sum,sumofsquares : float);
  395. {$endif FPC_HAS_TYPE_DOUBLE}
  396. {$ifdef FPC_HAS_TYPE_EXTENDED}
  397. function SumOfSquares(const data : array of Extended) : float;inline;
  398. function SumOfSquares(const data : PExtended; Const N : Integer) : float;
  399. { calculates the sum and the sum of squares of data }
  400. procedure SumsAndSquares(const data : array of Extended;
  401. var sum,sumofsquares : float);inline;
  402. procedure SumsAndSquares(const data : PExtended; Const N : Integer;
  403. var sum,sumofsquares : float);
  404. {$endif FPC_HAS_TYPE_EXTENDED}
  405. {$ifdef FPC_HAS_TYPE_SINGLE}
  406. function MinValue(const data : array of Single) : Single;inline;
  407. function MinValue(const data : PSingle; Const N : Integer) : Single;
  408. function MaxValue(const data : array of Single) : Single;inline;
  409. function MaxValue(const data : PSingle; Const N : Integer) : Single;
  410. {$endif FPC_HAS_TYPE_SINGLE}
  411. {$ifdef FPC_HAS_TYPE_DOUBLE}
  412. function MinValue(const data : array of Double) : Double;inline;
  413. function MinValue(const data : PDouble; Const N : Integer) : Double;
  414. function MaxValue(const data : array of Double) : Double;inline;
  415. function MaxValue(const data : PDouble; Const N : Integer) : Double;
  416. {$endif FPC_HAS_TYPE_DOUBLE}
  417. {$ifdef FPC_HAS_TYPE_EXTENDED}
  418. function MinValue(const data : array of Extended) : Extended;inline;
  419. function MinValue(const data : PExtended; Const N : Integer) : Extended;
  420. function MaxValue(const data : array of Extended) : Extended;inline;
  421. function MaxValue(const data : PExtended; Const N : Integer) : Extended;
  422. {$endif FPC_HAS_TYPE_EXTENDED}
  423. function MinValue(const data : array of integer) : Integer;inline;
  424. function MinValue(const Data : PInteger; Const N : Integer): Integer;
  425. function MaxValue(const data : array of integer) : Integer;inline;
  426. function MaxValue(const data : PInteger; Const N : Integer) : Integer;
  427. { returns random values with gaussian distribution }
  428. function RandG(mean,stddev : float) : float;
  429. function RandomRange(const aFrom, aTo: Integer): Integer;
  430. function RandomRange(const aFrom, aTo: Int64): Int64;
  431. {$ifdef FPC_HAS_TYPE_SINGLE}
  432. { calculates the standard deviation }
  433. function StdDev(const data : array of Single) : float;inline;
  434. function StdDev(const data : PSingle; Const N : Integer) : float;
  435. { calculates the mean and stddev }
  436. procedure MeanAndStdDev(const data : array of Single;
  437. var mean,stddev : float);inline;
  438. procedure MeanAndStdDev(const data : PSingle;
  439. Const N : Longint;var mean,stddev : float);
  440. function Variance(const data : array of Single) : float;inline;
  441. function TotalVariance(const data : array of Single) : float;inline;
  442. function Variance(const data : PSingle; Const N : Integer) : float;
  443. function TotalVariance(const data : PSingle; Const N : Integer) : float;
  444. { Population (aka uncorrected) variance and standard deviation }
  445. function PopnStdDev(const data : array of Single) : float;inline;
  446. function PopnStdDev(const data : PSingle; Const N : Integer) : float;
  447. function PopnVariance(const data : PSingle; Const N : Integer) : float;
  448. function PopnVariance(const data : array of Single) : float;inline;
  449. procedure MomentSkewKurtosis(const data : array of Single;
  450. out m1,m2,m3,m4,skew,kurtosis : float);inline;
  451. procedure MomentSkewKurtosis(const data : PSingle; Const N : Integer;
  452. out m1,m2,m3,m4,skew,kurtosis : float);
  453. { geometrical function }
  454. { returns the euclidean L2 norm }
  455. function Norm(const data : array of Single) : float;inline;
  456. function Norm(const data : PSingle; Const N : Integer) : float;
  457. {$endif FPC_HAS_TYPE_SINGLE}
  458. {$ifdef FPC_HAS_TYPE_DOUBLE}
  459. { calculates the standard deviation }
  460. function StdDev(const data : array of Double) : float;inline;
  461. function StdDev(const data : PDouble; Const N : Integer) : float;
  462. { calculates the mean and stddev }
  463. procedure MeanAndStdDev(const data : array of Double;
  464. var mean,stddev : float);inline;
  465. procedure MeanAndStdDev(const data : PDouble;
  466. Const N : Longint;var mean,stddev : float);
  467. function Variance(const data : array of Double) : float;inline;
  468. function TotalVariance(const data : array of Double) : float;inline;
  469. function Variance(const data : PDouble; Const N : Integer) : float;
  470. function TotalVariance(const data : PDouble; Const N : Integer) : float;
  471. { Population (aka uncorrected) variance and standard deviation }
  472. function PopnStdDev(const data : array of Double) : float;inline;
  473. function PopnStdDev(const data : PDouble; Const N : Integer) : float;
  474. function PopnVariance(const data : PDouble; Const N : Integer) : float;
  475. function PopnVariance(const data : array of Double) : float;inline;
  476. procedure MomentSkewKurtosis(const data : array of Double;
  477. out m1,m2,m3,m4,skew,kurtosis : float);inline;
  478. procedure MomentSkewKurtosis(const data : PDouble; Const N : Integer;
  479. out m1,m2,m3,m4,skew,kurtosis : float);
  480. { geometrical function }
  481. { returns the euclidean L2 norm }
  482. function Norm(const data : array of double) : float;inline;
  483. function Norm(const data : PDouble; Const N : Integer) : float;
  484. {$endif FPC_HAS_TYPE_DOUBLE}
  485. {$ifdef FPC_HAS_TYPE_EXTENDED}
  486. { calculates the standard deviation }
  487. function StdDev(const data : array of Extended) : float;inline;
  488. function StdDev(const data : PExtended; Const N : Integer) : float;
  489. { calculates the mean and stddev }
  490. procedure MeanAndStdDev(const data : array of Extended;
  491. var mean,stddev : float);inline;
  492. procedure MeanAndStdDev(const data : PExtended;
  493. Const N : Longint;var mean,stddev : float);
  494. function Variance(const data : array of Extended) : float;inline;
  495. function TotalVariance(const data : array of Extended) : float;inline;
  496. function Variance(const data : PExtended; Const N : Integer) : float;
  497. function TotalVariance(const data : PExtended; Const N : Integer) : float;
  498. { Population (aka uncorrected) variance and standard deviation }
  499. function PopnStdDev(const data : array of Extended) : float;inline;
  500. function PopnStdDev(const data : PExtended; Const N : Integer) : float;
  501. function PopnVariance(const data : PExtended; Const N : Integer) : float;
  502. function PopnVariance(const data : array of Extended) : float;inline;
  503. procedure MomentSkewKurtosis(const data : array of Extended;
  504. out m1,m2,m3,m4,skew,kurtosis : float);inline;
  505. procedure MomentSkewKurtosis(const data : PExtended; Const N : Integer;
  506. out m1,m2,m3,m4,skew,kurtosis : float);
  507. { geometrical function }
  508. { returns the euclidean L2 norm }
  509. function Norm(const data : array of Extended) : float;inline;
  510. function Norm(const data : PExtended; Const N : Integer) : float;
  511. {$endif FPC_HAS_TYPE_EXTENDED}
  512. { Financial functions }
  513. function FutureValue(ARate: Float; NPeriods: Integer;
  514. APayment, APresentValue: Float; APaymentTime: TPaymentTime): Float;
  515. function InterestRate(NPeriods: Integer; APayment, APresentValue, AFutureValue: Float;
  516. APaymentTime: TPaymentTime): Float;
  517. function NumberOfPeriods(ARate, APayment, APresentValue, AFutureValue: Float;
  518. APaymentTime: TPaymentTime): Float;
  519. function Payment(ARate: Float; NPeriods: Integer;
  520. APresentValue, AFutureValue: Float; APaymentTime: TPaymentTime): Float;
  521. function PresentValue(ARate: Float; NPeriods: Integer;
  522. APayment, AFutureValue: Float; APaymentTime: TPaymentTime): Float;
  523. { Misc functions }
  524. function IfThen(val:boolean;const iftrue:integer; const iffalse:integer= 0) :integer; inline; overload;
  525. function IfThen(val:boolean;const iftrue:int64 ; const iffalse:int64 = 0) :int64; inline; overload;
  526. function IfThen(val:boolean;const iftrue:double ; const iffalse:double =0.0):double; inline; overload;
  527. function CompareValue ( const A, B : Integer) : TValueRelationship; inline;
  528. function CompareValue ( const A, B : Int64) : TValueRelationship; inline;
  529. function CompareValue ( const A, B : QWord) : TValueRelationship; inline;
  530. {$ifdef FPC_HAS_TYPE_SINGLE}
  531. function CompareValue ( const A, B : Single; delta : Single = 0.0 ) : TValueRelationship; inline;
  532. {$endif}
  533. {$ifdef FPC_HAS_TYPE_DOUBLE}
  534. function CompareValue ( const A, B : Double; delta : Double = 0.0) : TValueRelationship; inline;
  535. {$endif}
  536. {$ifdef FPC_HAS_TYPE_EXTENDED}
  537. function CompareValue ( const A, B : Extended; delta : Extended = 0.0 ) : TValueRelationship; inline;
  538. {$endif}
  539. function RandomFrom(const AValues: array of Double): Double; overload;
  540. function RandomFrom(const AValues: array of Integer): Integer; overload;
  541. function RandomFrom(const AValues: array of Int64): Int64; overload;
  542. {$if FPC_FULLVERSION >=30101}
  543. generic function RandomFrom<T>(const AValues:array of T):T;
  544. {$endif}
  545. { cpu specific stuff }
  546. type
  547. TFPURoundingMode = system.TFPURoundingMode;
  548. TFPUPrecisionMode = system.TFPUPrecisionMode;
  549. TFPUException = system.TFPUException;
  550. TFPUExceptionMask = system.TFPUExceptionMask;
  551. function GetRoundMode: TFPURoundingMode;
  552. function SetRoundMode(const RoundMode: TFPURoundingMode): TFPURoundingMode;
  553. function GetPrecisionMode: TFPUPrecisionMode;
  554. function SetPrecisionMode(const Precision: TFPUPrecisionMode): TFPUPrecisionMode;
  555. function GetExceptionMask: TFPUExceptionMask;
  556. function SetExceptionMask(const Mask: TFPUExceptionMask): TFPUExceptionMask;
  557. procedure ClearExceptions(RaisePending: Boolean =true);
  558. implementation
  559. function copysign(x,y: float): float; forward; { returns abs(x)*sign(y) }
  560. { include cpu specific stuff }
  561. {$i mathu.inc}
  562. ResourceString
  563. SMathError = 'Math Error : %s';
  564. SInvalidArgument = 'Invalid argument';
  565. Procedure DoMathError(Const S : String);
  566. begin
  567. Raise EMathError.CreateFmt(SMathError,[S]);
  568. end;
  569. Procedure InvalidArgument;
  570. begin
  571. Raise EInvalidArgument.Create(SInvalidArgument);
  572. end;
  573. function Sign(const AValue: Integer): TValueSign;inline;
  574. begin
  575. result:=TValueSign(
  576. SarLongint(AValue,sizeof(AValue)*8-1) or { gives -1 for negative values, 0 otherwise }
  577. (longint(-AValue) shr (sizeof(AValue)*8-1)) { gives 1 for positive values, 0 otherwise }
  578. );
  579. end;
  580. function Sign(const AValue: Int64): TValueSign;inline;
  581. begin
  582. {$ifdef cpu64}
  583. result:=TValueSign(
  584. SarInt64(AValue,sizeof(AValue)*8-1) or
  585. (-AValue shr (sizeof(AValue)*8-1))
  586. );
  587. {$else cpu64}
  588. If Avalue<0 then
  589. Result:=NegativeValue
  590. else If Avalue>0 then
  591. Result:=PositiveValue
  592. else
  593. Result:=ZeroValue;
  594. {$endif}
  595. end;
  596. {$ifdef FPC_HAS_TYPE_SINGLE}
  597. function Sign(const AValue: Single): TValueSign;inline;
  598. begin
  599. Result:=ord(AValue>0.0)-ord(AValue<0.0);
  600. end;
  601. {$endif}
  602. function Sign(const AValue: Double): TValueSign;inline;
  603. begin
  604. Result:=ord(AValue>0.0)-ord(AValue<0.0);
  605. end;
  606. {$ifdef FPC_HAS_TYPE_EXTENDED}
  607. function Sign(const AValue: Extended): TValueSign;inline;
  608. begin
  609. Result:=ord(AValue>0.0)-ord(AValue<0.0);
  610. end;
  611. {$endif}
  612. function degtorad(deg : float) : float;inline;
  613. begin
  614. degtorad:=deg*(pi/180.0);
  615. end;
  616. function radtodeg(rad : float) : float;inline;
  617. begin
  618. radtodeg:=rad*(180.0/pi);
  619. end;
  620. function gradtorad(grad : float) : float;inline;
  621. begin
  622. gradtorad:=grad*(pi/200.0);
  623. end;
  624. function radtograd(rad : float) : float;inline;
  625. begin
  626. radtograd:=rad*(200.0/pi);
  627. end;
  628. function degtograd(deg : float) : float;inline;
  629. begin
  630. degtograd:=deg*(200.0/180.0);
  631. end;
  632. function gradtodeg(grad : float) : float;inline;
  633. begin
  634. gradtodeg:=grad*(180.0/200.0);
  635. end;
  636. function cycletorad(cycle : float) : float;inline;
  637. begin
  638. cycletorad:=(2*pi)*cycle;
  639. end;
  640. function radtocycle(rad : float) : float;inline;
  641. begin
  642. { avoid division }
  643. radtocycle:=rad*(1/(2*pi));
  644. end;
  645. {$ifdef FPC_HAS_TYPE_SINGLE}
  646. Function DegNormalize(deg : single) : single;
  647. begin
  648. Result:=Deg-Int(Deg/360)*360;
  649. If Result<0 then Result:=Result+360;
  650. end;
  651. {$ENDIF}
  652. {$ifdef FPC_HAS_TYPE_DOUBLE}
  653. Function DegNormalize(deg : double) : double; inline;
  654. begin
  655. Result:=Deg-Int(Deg/360)*360;
  656. If (Result<0) then Result:=Result+360;
  657. end;
  658. {$ENDIF}
  659. {$ifdef FPC_HAS_TYPE_EXTENDED}
  660. Function DegNormalize(deg : extended) : extended; inline;
  661. begin
  662. Result:=Deg-Int(Deg/360)*360;
  663. If Result<0 then Result:=Result+360;
  664. end;
  665. {$ENDIF}
  666. {$ifndef FPC_MATH_HAS_TAN}
  667. function tan(x : float) : float;
  668. var
  669. _sin,_cos : float;
  670. begin
  671. sincos(x,_sin,_cos);
  672. tan:=_sin/_cos;
  673. end;
  674. {$endif FPC_MATH_HAS_TAN}
  675. {$ifndef FPC_MATH_HAS_COTAN}
  676. function cotan(x : float) : float;
  677. var
  678. _sin,_cos : float;
  679. begin
  680. sincos(x,_sin,_cos);
  681. cotan:=_cos/_sin;
  682. end;
  683. {$endif FPC_MATH_HAS_COTAN}
  684. function cot(x : float) : float; inline;
  685. begin
  686. cot := cotan(x);
  687. end;
  688. {$ifndef FPC_MATH_HAS_SINCOS}
  689. {$ifdef FPC_HAS_TYPE_SINGLE}
  690. procedure sincos(theta : single;out sinus,cosinus : single);
  691. begin
  692. sinus:=sin(theta);
  693. cosinus:=cos(theta);
  694. end;
  695. {$endif}
  696. {$ifdef FPC_HAS_TYPE_DOUBLE}
  697. procedure sincos(theta : double;out sinus,cosinus : double);
  698. begin
  699. sinus:=sin(theta);
  700. cosinus:=cos(theta);
  701. end;
  702. {$endif}
  703. {$ifdef FPC_HAS_TYPE_EXTENDED}
  704. procedure sincos(theta : extended;out sinus,cosinus : extended);
  705. begin
  706. sinus:=sin(theta);
  707. cosinus:=cos(theta);
  708. end;
  709. {$endif}
  710. {$endif FPC_MATH_HAS_SINCOS}
  711. function secant(x : float) : float; inline;
  712. begin
  713. secant := 1 / cos(x);
  714. end;
  715. function cosecant(x : float) : float; inline;
  716. begin
  717. cosecant := 1 / sin(x);
  718. end;
  719. function sec(x : float) : float; inline;
  720. begin
  721. sec := secant(x);
  722. end;
  723. function csc(x : float) : float; inline;
  724. begin
  725. csc := cosecant(x);
  726. end;
  727. { arcsin and arccos functions from AMath library (C) Copyright 2009-2013 Wolfgang Ehrhardt }
  728. function arcsin(x : float) : float;
  729. begin
  730. arcsin:=arctan2(x,sqrt((1.0-x)*(1.0+x)));
  731. end;
  732. function Arccos(x : Float) : Float;
  733. begin
  734. if abs(x)=1.0 then
  735. if x<0.0 then
  736. arccos:=Pi
  737. else
  738. arccos:=0
  739. else
  740. arccos:=arctan2(sqrt((1.0-x)*(1.0+x)),x);
  741. end;
  742. {$ifndef FPC_MATH_HAS_ARCTAN2}
  743. function arctan2(y,x : float) : float;
  744. begin
  745. if x=0 then
  746. begin
  747. if y=0 then
  748. result:=0.0
  749. else if y>0 then
  750. result:=pi/2
  751. else
  752. result:=-pi/2;
  753. end
  754. else
  755. begin
  756. result:=ArcTan(y/x);
  757. if x<0 then
  758. if y<0 then
  759. result:=result-pi
  760. else
  761. result:=result+pi;
  762. end;
  763. end;
  764. {$endif FPC_MATH_HAS_ARCTAN2}
  765. function cosh(x : float) : float;
  766. var
  767. temp : float;
  768. begin
  769. temp:=exp(x);
  770. cosh:=0.5*(temp+1.0/temp);
  771. end;
  772. function sinh(x : float) : float;
  773. var
  774. temp : float;
  775. begin
  776. temp:=exp(x);
  777. { copysign ensures that sinh(-0.0)=-0.0 }
  778. sinh:=copysign(0.5*(temp-1.0/temp),x);
  779. end;
  780. function tanh(x : float) : float;
  781. var
  782. tmp:float;
  783. begin
  784. if x < 0 then begin
  785. tmp:=exp(2*x);
  786. result:=(tmp-1)/(1+tmp)
  787. end
  788. else begin
  789. tmp:=exp(-2*x);
  790. result:=(1-tmp)/(1+tmp)
  791. end;
  792. end;
  793. function arccosh(x : float) : float; inline;
  794. begin
  795. arccosh:=arcosh(x);
  796. end;
  797. function arcsinh(x : float) : float;inline;
  798. begin
  799. arcsinh:=arsinh(x);
  800. end;
  801. function arctanh(x : float) : float;inline;
  802. begin
  803. arctanh:=artanh(x);
  804. end;
  805. function arcosh(x : float) : float;
  806. begin
  807. { Provides accuracy about 4*eps near 1.0 }
  808. arcosh:=Ln(x+Sqrt((x-1.0)*(x+1.0)));
  809. end;
  810. function arsinh(x : float) : float;
  811. var
  812. z: float;
  813. begin
  814. z:=abs(x);
  815. z:=Ln(z+Sqrt(1+z*z));
  816. { copysign ensures that arsinh(-Inf)=-Inf and arsinh(-0.0)=-0.0 }
  817. arsinh:=copysign(z,x);
  818. end;
  819. function artanh(x : float) : float;
  820. begin
  821. artanh:=(lnxp1(x)-lnxp1(-x))*0.5;
  822. end;
  823. { hypot function from AMath library (C) Copyright 2009-2013 Wolfgang Ehrhardt }
  824. function hypot(x,y : float) : float;
  825. begin
  826. x:=abs(x);
  827. y:=abs(y);
  828. if (x>y) then
  829. hypot:=x*sqrt(1.0+sqr(y/x))
  830. else if (x>0.0) then
  831. hypot:=y*sqrt(1.0+sqr(x/y))
  832. else
  833. hypot:=y;
  834. end;
  835. function log10(x : float) : float;
  836. begin
  837. log10:=ln(x)*0.43429448190325182765; { 1/ln(10) }
  838. end;
  839. {$ifndef FPC_MATH_HAS_LOG2}
  840. function log2(x : float) : float;
  841. begin
  842. log2:=ln(x)*1.4426950408889634079; { 1/ln(2) }
  843. end;
  844. {$endif FPC_MATH_HAS_LOG2}
  845. function logn(n,x : float) : float;
  846. begin
  847. logn:=ln(x)/ln(n);
  848. end;
  849. { lnxp1 function from AMath library (C) Copyright 2009-2013 Wolfgang Ehrhardt }
  850. function lnxp1(x : float) : float;
  851. var
  852. y: float;
  853. begin
  854. if (x>=4.0) then
  855. lnxp1:=ln(1.0+x)
  856. else
  857. begin
  858. y:=1.0+x;
  859. if (y=1.0) then
  860. lnxp1:=x
  861. else
  862. begin
  863. lnxp1:=ln(y); { lnxp1(-1) = ln(0) = -Inf }
  864. if y>0.0 then
  865. lnxp1:=lnxp1+(x-(y-1.0))/y;
  866. end;
  867. end;
  868. end;
  869. function power(base,exponent : float) : float;
  870. begin
  871. if Exponent=0.0 then
  872. result:=1.0
  873. else if (base=0.0) and (exponent>0.0) then
  874. result:=0.0
  875. else if (abs(exponent)<=maxint) and (frac(exponent)=0.0) then
  876. result:=intpower(base,trunc(exponent))
  877. else
  878. result:=exp(exponent * ln (base));
  879. end;
  880. function intpower(base : float;exponent : longint) : float;
  881. begin
  882. if exponent<0 then
  883. begin
  884. base:=1.0/base;
  885. exponent:=-exponent;
  886. end;
  887. intpower:=1.0;
  888. while exponent<>0 do
  889. begin
  890. if exponent and 1<>0 then
  891. intpower:=intpower*base;
  892. exponent:=exponent shr 1;
  893. base:=sqr(base);
  894. end;
  895. end;
  896. operator ** (bas,expo : float) e: float; inline;
  897. begin
  898. e:=power(bas,expo);
  899. end;
  900. operator ** (bas,expo : int64) i: int64; inline;
  901. begin
  902. i:=round(intpower(bas,expo));
  903. end;
  904. function ceil(x : float) : integer;
  905. begin
  906. Result:=Trunc(x)+ord(Frac(x)>0);
  907. end;
  908. function ceil64(x: float): Int64;
  909. begin
  910. Result:=Trunc(x)+ord(Frac(x)>0);
  911. end;
  912. function floor(x : float) : integer;
  913. begin
  914. Result:=Trunc(x)-ord(Frac(x)<0);
  915. end;
  916. function floor64(x: float): Int64;
  917. begin
  918. Result:=Trunc(x)-ord(Frac(x)<0);
  919. end;
  920. // Correction for "rounding to nearest, ties to even".
  921. // RoundToNearestTieToEven(QWE.RTYUIOP) = QWE + TieToEven(ER, TYUIOP <> 0).
  922. function TieToEven(AB: cardinal; somethingAfter: boolean): cardinal;
  923. begin
  924. result := AB and 1;
  925. if (result <> 0) and not somethingAfter then
  926. result := AB shr 1;
  927. end;
  928. {$ifdef FPC_HAS_TYPE_SINGLE}
  929. procedure Frexp(X: single; out Mantissa: single; out Exponent: integer);
  930. var
  931. M: uint32;
  932. E, ExtraE: int32;
  933. begin
  934. Mantissa := X;
  935. E := TSingleRec(X).Exp;
  936. if (E > 0) and (E < 2 * TSingleRec.Bias + 1) then
  937. begin
  938. // Normal.
  939. TSingleRec(Mantissa).Exp := TSingleRec.Bias - 1;
  940. Exponent := E - (TSingleRec.Bias - 1);
  941. exit;
  942. end;
  943. if E = 0 then
  944. begin
  945. M := TSingleRec(X).Frac;
  946. if M <> 0 then
  947. begin
  948. // Subnormal.
  949. ExtraE := 23 - BsrDWord(M);
  950. TSingleRec(Mantissa).Frac := M shl ExtraE; // "and (1 shl 23 - 1)" required to remove starting 1, but .SetFrac already does it.
  951. TSingleRec(Mantissa).Exp := TSingleRec.Bias - 1;
  952. Exponent := -TSingleRec.Bias + 2 - ExtraE;
  953. exit;
  954. end;
  955. end;
  956. // ±0, ±Inf, NaN.
  957. Exponent := 0;
  958. end;
  959. function Ldexp(X: single; p: integer): single;
  960. var
  961. M, E: uint32;
  962. xp, sh: integer;
  963. begin
  964. E := TSingleRec(X).Exp;
  965. if (E = 0) and (TSingleRec(X).Frac = 0) or (E = 2 * TSingleRec.Bias + 1) then
  966. // ±0, ±Inf, NaN.
  967. exit(X);
  968. Frexp(X, result, xp);
  969. inc(xp, p);
  970. if (xp >= -TSingleRec.Bias + 2) and (xp <= TSingleRec.Bias + 1) then
  971. // Normalized.
  972. TSingleRec(result).Exp := xp + (TSingleRec.Bias - 1)
  973. else if xp > TSingleRec.Bias + 1 then
  974. begin
  975. // Overflow.
  976. TSingleRec(result).Exp := 2 * TSingleRec.Bias + 1;
  977. TSingleRec(result).Frac := 0;
  978. end else
  979. begin
  980. TSingleRec(result).Exp := 0;
  981. if xp >= -TSingleRec.Bias + 2 - 23 then
  982. begin
  983. // Denormalized.
  984. M := TSingleRec(result).Frac or uint32(1) shl 23;
  985. sh := -TSingleRec.Bias + 1 - xp;
  986. TSingleRec(result).Frac := M shr (sh + 1) + TieToEven(M shr sh and 3, M and (uint32(1) shl sh - 1) <> 0);
  987. end else
  988. // Underflow.
  989. TSingleRec(result).Frac := 0;
  990. end;
  991. end;
  992. {$endif}
  993. {$ifdef FPC_HAS_TYPE_DOUBLE}
  994. procedure Frexp(X: double; out Mantissa: double; out Exponent: integer);
  995. var
  996. M: uint64;
  997. E, ExtraE: int32;
  998. begin
  999. Mantissa := X;
  1000. E := TDoubleRec(X).Exp;
  1001. if (E > 0) and (E < 2 * TDoubleRec.Bias + 1) then
  1002. begin
  1003. // Normal.
  1004. TDoubleRec(Mantissa).Exp := TDoubleRec.Bias - 1;
  1005. Exponent := E - (TDoubleRec.Bias - 1);
  1006. exit;
  1007. end;
  1008. if E = 0 then
  1009. begin
  1010. M := TDoubleRec(X).Frac;
  1011. if M <> 0 then
  1012. begin
  1013. // Subnormal.
  1014. ExtraE := 52 - BsrQWord(M);
  1015. TDoubleRec(Mantissa).Frac := M shl ExtraE; // "and (1 shl 52 - 1)" required to remove starting 1, but .SetFrac already does it.
  1016. TDoubleRec(Mantissa).Exp := TDoubleRec.Bias - 1;
  1017. Exponent := -TDoubleRec.Bias + 2 - ExtraE;
  1018. exit;
  1019. end;
  1020. end;
  1021. // ±0, ±Inf, NaN.
  1022. Exponent := 0;
  1023. end;
  1024. function Ldexp(X: double; p: integer): double;
  1025. var
  1026. M: uint64;
  1027. E: uint32;
  1028. xp, sh: integer;
  1029. begin
  1030. E := TDoubleRec(X).Exp;
  1031. if (E = 0) and (TDoubleRec(X).Frac = 0) or (E = 2 * TDoubleRec.Bias + 1) then
  1032. // ±0, ±Inf, NaN.
  1033. exit(X);
  1034. Frexp(X, result, xp);
  1035. inc(xp, p);
  1036. if (xp >= -TDoubleRec.Bias + 2) and (xp <= TDoubleRec.Bias + 1) then
  1037. // Normalized.
  1038. TDoubleRec(result).Exp := xp + (TDoubleRec.Bias - 1)
  1039. else if xp > TDoubleRec.Bias + 1 then
  1040. begin
  1041. // Overflow.
  1042. TDoubleRec(result).Exp := 2 * TDoubleRec.Bias + 1;
  1043. TDoubleRec(result).Frac := 0;
  1044. end else
  1045. begin
  1046. TDoubleRec(result).Exp := 0;
  1047. if xp >= -TDoubleRec.Bias + 2 - 52 then
  1048. begin
  1049. // Denormalized.
  1050. M := TDoubleRec(result).Frac or uint64(1) shl 52;
  1051. sh := -TSingleRec.Bias + 1 - xp;
  1052. TDoubleRec(result).Frac := M shr (sh + 1) + TieToEven(M shr sh and 3, M and (uint64(1) shl sh - 1) <> 0);
  1053. end else
  1054. // Underflow.
  1055. TDoubleRec(result).Frac := 0;
  1056. end;
  1057. end;
  1058. {$endif}
  1059. {$ifdef FPC_HAS_TYPE_EXTENDED}
  1060. procedure Frexp(X: extended; out Mantissa: extended; out Exponent: integer);
  1061. var
  1062. M: uint64;
  1063. E, ExtraE: int32;
  1064. begin
  1065. Mantissa := X;
  1066. E := TExtended80Rec(X).Exp;
  1067. if (E > 0) and (E < 2 * TExtended80Rec.Bias + 1) then
  1068. begin
  1069. // Normal.
  1070. TExtended80Rec(Mantissa).Exp := TExtended80Rec.Bias - 1;
  1071. Exponent := E - (TExtended80Rec.Bias - 1);
  1072. exit;
  1073. end;
  1074. if E = 0 then
  1075. begin
  1076. M := TExtended80Rec(X).Frac;
  1077. if M <> 0 then
  1078. begin
  1079. // Subnormal. Extended has explicit starting 1.
  1080. ExtraE := 63 - BsrQWord(M);
  1081. TExtended80Rec(Mantissa).Frac := M shl ExtraE;
  1082. TExtended80Rec(Mantissa).Exp := TExtended80Rec.Bias - 1;
  1083. Exponent := -TExtended80Rec.Bias + 2 - ExtraE;
  1084. exit;
  1085. end;
  1086. end;
  1087. // ±0, ±Inf, NaN.
  1088. Exponent := 0;
  1089. end;
  1090. function Ldexp(X: extended; p: integer): extended;
  1091. var
  1092. M: uint64;
  1093. E: uint32;
  1094. xp, sh: integer;
  1095. begin
  1096. E := TExtended80Rec(X).Exp;
  1097. if (E = 0) and (TExtended80Rec(X).Frac = 0) or (E = 2 * TExtended80Rec.Bias + 1) then
  1098. // ±0, ±Inf, NaN.
  1099. exit(X);
  1100. Frexp(X, result, xp);
  1101. inc(xp, p);
  1102. if (xp >= -TExtended80Rec.Bias + 2) and (xp <= TExtended80Rec.Bias + 1) then
  1103. // Normalized.
  1104. TExtended80Rec(result).Exp := xp + (TExtended80Rec.Bias - 1)
  1105. else if xp > TExtended80Rec.Bias + 1 then
  1106. begin
  1107. // Overflow.
  1108. TExtended80Rec(result).Exp := 2 * TExtended80Rec.Bias + 1;
  1109. TExtended80Rec(result).Frac := uint64(1) shl 63;
  1110. end
  1111. else if xp >= -TExtended80Rec.Bias + 2 - 63 then
  1112. begin
  1113. // Denormalized... usually.
  1114. // Mantissa of subnormal 'extended' (Exp = 0) must always start with 0.
  1115. // If the calculated mantissa starts with 1, extended instead becomes normalized with Exp = 1.
  1116. M := TExtended80Rec(result).Frac;
  1117. sh := -TExtended80Rec.Bias + 1 - xp;
  1118. M := M shr (sh + 1) + TieToEven(M shr sh and 3, M and (uint64(1) shl sh - 1) <> 0);
  1119. TExtended80Rec(result).Exp := M shr 63;
  1120. TExtended80Rec(result).Frac := M;
  1121. end else
  1122. begin
  1123. // Underflow.
  1124. TExtended80Rec(result).Exp := 0;
  1125. TExtended80Rec(result).Frac := 0;
  1126. end;
  1127. end;
  1128. {$endif}
  1129. const
  1130. { Cutoff for https://en.wikipedia.org/wiki/Pairwise_summation; sums of at least this many elements are split in two halves. }
  1131. RecursiveSumThreshold=12;
  1132. {$ifdef FPC_HAS_TYPE_SINGLE}
  1133. function mean(const data : array of Single) : float;
  1134. begin
  1135. Result:=Mean(PSingle(@data[0]),High(Data)+1);
  1136. end;
  1137. function mean(const data : PSingle; Const N : longint) : float;
  1138. begin
  1139. mean:=sum(Data,N);
  1140. mean:=mean/N;
  1141. end;
  1142. function sum(const data : array of Single) : float;inline;
  1143. begin
  1144. Result:=Sum(PSingle(@Data[0]),High(Data)+1);
  1145. end;
  1146. function sum(const data : PSingle;Const N : longint) : float;
  1147. var
  1148. i : SizeInt;
  1149. begin
  1150. if N>=RecursiveSumThreshold then
  1151. result:=sum(data,longword(N) div 2)+sum(data+longword(N) div 2,N-longword(N) div 2)
  1152. else
  1153. begin
  1154. result:=0;
  1155. for i:=0 to N-1 do
  1156. result:=result+data[i];
  1157. end;
  1158. end;
  1159. {$endif FPC_HAS_TYPE_SINGLE}
  1160. {$ifdef FPC_HAS_TYPE_DOUBLE}
  1161. function mean(const data : array of Double) : float; inline;
  1162. begin
  1163. Result:=Mean(PDouble(@data[0]),High(Data)+1);
  1164. end;
  1165. function mean(const data : PDouble; Const N : longint) : float;
  1166. begin
  1167. mean:=sum(Data,N);
  1168. mean:=mean/N;
  1169. end;
  1170. function sum(const data : array of Double) : float; inline;
  1171. begin
  1172. Result:=Sum(PDouble(@Data[0]),High(Data)+1);
  1173. end;
  1174. function sum(const data : PDouble;Const N : longint) : float;
  1175. var
  1176. i : SizeInt;
  1177. begin
  1178. if N>=RecursiveSumThreshold then
  1179. result:=sum(data,longword(N) div 2)+sum(data+longword(N) div 2,N-longword(N) div 2)
  1180. else
  1181. begin
  1182. result:=0;
  1183. for i:=0 to N-1 do
  1184. result:=result+data[i];
  1185. end;
  1186. end;
  1187. {$endif FPC_HAS_TYPE_DOUBLE}
  1188. {$ifdef FPC_HAS_TYPE_EXTENDED}
  1189. function mean(const data : array of Extended) : float;
  1190. begin
  1191. Result:=Mean(PExtended(@data[0]),High(Data)+1);
  1192. end;
  1193. function mean(const data : PExtended; Const N : longint) : float;
  1194. begin
  1195. mean:=sum(Data,N);
  1196. mean:=mean/N;
  1197. end;
  1198. function sum(const data : array of Extended) : float; inline;
  1199. begin
  1200. Result:=Sum(PExtended(@Data[0]),High(Data)+1);
  1201. end;
  1202. function sum(const data : PExtended;Const N : longint) : float;
  1203. var
  1204. i : SizeInt;
  1205. begin
  1206. if N>=RecursiveSumThreshold then
  1207. result:=sum(data,longword(N) div 2)+sum(data+longword(N) div 2,N-longword(N) div 2)
  1208. else
  1209. begin
  1210. result:=0;
  1211. for i:=0 to N-1 do
  1212. result:=result+data[i];
  1213. end;
  1214. end;
  1215. {$endif FPC_HAS_TYPE_EXTENDED}
  1216. function sumInt(const data : PInt64;Const N : longint) : Int64;
  1217. var
  1218. i : SizeInt;
  1219. begin
  1220. sumInt:=0;
  1221. for i:=0 to N-1 do
  1222. sumInt:=sumInt+data[i];
  1223. end;
  1224. function sumInt(const data : array of Int64) : Int64; inline;
  1225. begin
  1226. Result:=SumInt(PInt64(@Data[0]),High(Data)+1);
  1227. end;
  1228. function mean(const data : PInt64; const N : Longint):Float;
  1229. begin
  1230. mean:=sumInt(Data,N);
  1231. mean:=mean/N;
  1232. end;
  1233. function mean(const data: array of Int64):Float;
  1234. begin
  1235. mean:=mean(PInt64(@data[0]),High(Data)+1);
  1236. end;
  1237. function sumInt(const data : PInteger; Const N : longint) : Int64;
  1238. var
  1239. i : SizeInt;
  1240. begin
  1241. sumInt:=0;
  1242. for i:=0 to N-1 do
  1243. sumInt:=sumInt+data[i];
  1244. end;
  1245. function sumInt(const data : array of Integer) : Int64;inline;
  1246. begin
  1247. Result:=sumInt(PInteger(@Data[0]),High(Data)+1);
  1248. end;
  1249. function mean(const data : PInteger; const N : Longint):Float;
  1250. begin
  1251. mean:=sumInt(Data,N);
  1252. mean:=mean/N;
  1253. end;
  1254. function mean(const data: array of Integer):Float;
  1255. begin
  1256. mean:=mean(PInteger(@data[0]),High(Data)+1);
  1257. end;
  1258. {$ifdef FPC_HAS_TYPE_SINGLE}
  1259. function sumofsquares(const data : array of Single) : float; inline;
  1260. begin
  1261. Result:=sumofsquares(PSingle(@data[0]),High(Data)+1);
  1262. end;
  1263. function sumofsquares(const data : PSingle; Const N : Integer) : float;
  1264. var
  1265. i : SizeInt;
  1266. begin
  1267. if N>=RecursiveSumThreshold then
  1268. result:=sumofsquares(data,cardinal(N) div 2)+sumofsquares(data+cardinal(N) div 2,N-cardinal(N) div 2)
  1269. else
  1270. begin
  1271. result:=0;
  1272. for i:=0 to N-1 do
  1273. result:=result+sqr(data[i]);
  1274. end;
  1275. end;
  1276. procedure sumsandsquares(const data : array of Single;
  1277. var sum,sumofsquares : float); inline;
  1278. begin
  1279. sumsandsquares (PSingle(@Data[0]),High(Data)+1,Sum,sumofsquares);
  1280. end;
  1281. procedure sumsandsquares(const data : PSingle; Const N : Integer;
  1282. var sum,sumofsquares : float);
  1283. var
  1284. i : SizeInt;
  1285. temp,tsum,tsumofsquares,sum0,sumofsquares0,sum1,sumofsquares1 : float;
  1286. begin
  1287. if N>=RecursiveSumThreshold then
  1288. begin
  1289. sumsandsquares(data,cardinal(N) div 2,sum0,sumofsquares0);
  1290. sumsandsquares(data+cardinal(N) div 2,N-cardinal(N) div 2,sum1,sumofsquares1);
  1291. sum:=sum0+sum1;
  1292. sumofsquares:=sumofsquares0+sumofsquares1;
  1293. end
  1294. else
  1295. begin
  1296. tsum:=0;
  1297. tsumofsquares:=0;
  1298. for i:=0 to N-1 do
  1299. begin
  1300. temp:=data[i];
  1301. tsum:=tsum+temp;
  1302. tsumofsquares:=tsumofsquares+sqr(temp);
  1303. end;
  1304. sum:=tsum;
  1305. sumofsquares:=tsumofsquares;
  1306. end;
  1307. end;
  1308. {$endif FPC_HAS_TYPE_SINGLE}
  1309. {$ifdef FPC_HAS_TYPE_DOUBLE}
  1310. function sumofsquares(const data : array of Double) : float; inline;
  1311. begin
  1312. Result:=sumofsquares(PDouble(@data[0]),High(Data)+1);
  1313. end;
  1314. function sumofsquares(const data : PDouble; Const N : Integer) : float;
  1315. var
  1316. i : SizeInt;
  1317. begin
  1318. if N>=RecursiveSumThreshold then
  1319. result:=sumofsquares(data,cardinal(N) div 2)+sumofsquares(data+cardinal(N) div 2,N-cardinal(N) div 2)
  1320. else
  1321. begin
  1322. result:=0;
  1323. for i:=0 to N-1 do
  1324. result:=result+sqr(data[i]);
  1325. end;
  1326. end;
  1327. procedure sumsandsquares(const data : array of Double;
  1328. var sum,sumofsquares : float);
  1329. begin
  1330. sumsandsquares (PDouble(@Data[0]),High(Data)+1,Sum,sumofsquares);
  1331. end;
  1332. procedure sumsandsquares(const data : PDouble; Const N : Integer;
  1333. var sum,sumofsquares : float);
  1334. var
  1335. i : SizeInt;
  1336. temp,tsum,tsumofsquares,sum0,sumofsquares0,sum1,sumofsquares1 : float;
  1337. begin
  1338. if N>=RecursiveSumThreshold then
  1339. begin
  1340. sumsandsquares(data,cardinal(N) div 2,sum0,sumofsquares0);
  1341. sumsandsquares(data+cardinal(N) div 2,N-cardinal(N) div 2,sum1,sumofsquares1);
  1342. sum:=sum0+sum1;
  1343. sumofsquares:=sumofsquares0+sumofsquares1;
  1344. end
  1345. else
  1346. begin
  1347. tsum:=0;
  1348. tsumofsquares:=0;
  1349. for i:=0 to N-1 do
  1350. begin
  1351. temp:=data[i];
  1352. tsum:=tsum+temp;
  1353. tsumofsquares:=tsumofsquares+sqr(temp);
  1354. end;
  1355. sum:=tsum;
  1356. sumofsquares:=tsumofsquares;
  1357. end;
  1358. end;
  1359. {$endif FPC_HAS_TYPE_DOUBLE}
  1360. {$ifdef FPC_HAS_TYPE_EXTENDED}
  1361. function sumofsquares(const data : array of Extended) : float; inline;
  1362. begin
  1363. Result:=sumofsquares(PExtended(@data[0]),High(Data)+1);
  1364. end;
  1365. function sumofsquares(const data : PExtended; Const N : Integer) : float;
  1366. var
  1367. i : SizeInt;
  1368. begin
  1369. if N>=RecursiveSumThreshold then
  1370. result:=sumofsquares(data,cardinal(N) div 2)+sumofsquares(data+cardinal(N) div 2,N-cardinal(N) div 2)
  1371. else
  1372. begin
  1373. result:=0;
  1374. for i:=0 to N-1 do
  1375. result:=result+sqr(data[i]);
  1376. end;
  1377. end;
  1378. procedure sumsandsquares(const data : array of Extended;
  1379. var sum,sumofsquares : float); inline;
  1380. begin
  1381. sumsandsquares (PExtended(@Data[0]),High(Data)+1,Sum,sumofsquares);
  1382. end;
  1383. procedure sumsandsquares(const data : PExtended; Const N : Integer;
  1384. var sum,sumofsquares : float);
  1385. var
  1386. i : SizeInt;
  1387. temp,tsum,tsumofsquares,sum0,sumofsquares0,sum1,sumofsquares1 : float;
  1388. begin
  1389. if N>=RecursiveSumThreshold then
  1390. begin
  1391. sumsandsquares(data,cardinal(N) div 2,sum0,sumofsquares0);
  1392. sumsandsquares(data+cardinal(N) div 2,N-cardinal(N) div 2,sum1,sumofsquares1);
  1393. sum:=sum0+sum1;
  1394. sumofsquares:=sumofsquares0+sumofsquares1;
  1395. end
  1396. else
  1397. begin
  1398. tsum:=0;
  1399. tsumofsquares:=0;
  1400. for i:=0 to N-1 do
  1401. begin
  1402. temp:=data[i];
  1403. tsum:=tsum+temp;
  1404. tsumofsquares:=tsumofsquares+sqr(temp);
  1405. end;
  1406. sum:=tsum;
  1407. sumofsquares:=tsumofsquares;
  1408. end;
  1409. end;
  1410. {$endif FPC_HAS_TYPE_EXTENDED}
  1411. function randg(mean,stddev : float) : float;
  1412. Var U1,S2 : Float;
  1413. begin
  1414. repeat
  1415. u1:= 2*random-1;
  1416. S2:=Sqr(U1)+sqr(2*random-1);
  1417. until s2<1;
  1418. randg:=Sqrt(-2*ln(S2)/S2)*u1*stddev+Mean;
  1419. end;
  1420. function RandomRange(const aFrom, aTo: Integer): Integer;
  1421. begin
  1422. Result:=Random(Abs(aFrom-aTo))+Min(aTo,AFrom);
  1423. end;
  1424. function RandomRange(const aFrom, aTo: Int64): Int64;
  1425. begin
  1426. Result:=Random(Abs(aFrom-aTo))+Min(aTo,AFrom);
  1427. end;
  1428. {$ifdef FPC_HAS_TYPE_SINGLE}
  1429. procedure MeanAndTotalVariance
  1430. (const data: PSingle; N: LongInt; var mu, variance: float);
  1431. function CalcVariance(data: PSingle; N: SizeInt; mu: float): float;
  1432. var
  1433. i: SizeInt;
  1434. begin
  1435. if N>=RecursiveSumThreshold then
  1436. result:=CalcVariance(data,SizeUint(N) div 2,mu)+CalcVariance(data+SizeUint(N) div 2,N-SizeUint(N) div 2,mu)
  1437. else
  1438. begin
  1439. result:=0;
  1440. for i:=0 to N-1 do
  1441. result:=result+Sqr(data[i]-mu);
  1442. end;
  1443. end;
  1444. begin
  1445. mu := Mean( data, N );
  1446. variance := CalcVariance( data, N, mu );
  1447. end;
  1448. function stddev(const data : array of Single) : float; inline;
  1449. begin
  1450. Result:=Stddev(PSingle(@Data[0]),High(Data)+1);
  1451. end;
  1452. function stddev(const data : PSingle; Const N : Integer) : float;
  1453. begin
  1454. StdDev:=Sqrt(Variance(Data,N));
  1455. end;
  1456. procedure meanandstddev(const data : array of Single;
  1457. var mean,stddev : float); inline;
  1458. begin
  1459. Meanandstddev(PSingle(@Data[0]),High(Data)+1,Mean,stddev);
  1460. end;
  1461. procedure meanandstddev
  1462. ( const data: PSingle;
  1463. const N: Longint;
  1464. var mean,
  1465. stdDev: Float
  1466. );
  1467. var totalVariance: float;
  1468. begin
  1469. MeanAndTotalVariance( data, N, mean, totalVariance );
  1470. if N < 2 then stdDev := 0
  1471. else stdDev := Sqrt( totalVariance / ( N - 1 ) );
  1472. end;
  1473. function variance(const data : array of Single) : float; inline;
  1474. begin
  1475. Variance:=Variance(PSingle(@Data[0]),High(Data)+1);
  1476. end;
  1477. function variance(const data : PSingle; Const N : Integer) : float;
  1478. begin
  1479. If N=1 then
  1480. Result:=0
  1481. else
  1482. Result:=TotalVariance(Data,N)/(N-1);
  1483. end;
  1484. function totalvariance(const data : array of Single) : float; inline;
  1485. begin
  1486. Result:=TotalVariance(PSingle(@Data[0]),High(Data)+1);
  1487. end;
  1488. function totalvariance(const data : PSingle; const N : Integer) : float;
  1489. var mu: float;
  1490. begin
  1491. MeanAndTotalVariance( data, N, mu, result );
  1492. end;
  1493. function popnstddev(const data : array of Single) : float;
  1494. begin
  1495. PopnStdDev:=Sqrt(PopnVariance(PSingle(@Data[0]),High(Data)+1));
  1496. end;
  1497. function popnstddev(const data : PSingle; Const N : Integer) : float;
  1498. begin
  1499. PopnStdDev:=Sqrt(PopnVariance(Data,N));
  1500. end;
  1501. function popnvariance(const data : array of Single) : float; inline;
  1502. begin
  1503. popnvariance:=popnvariance(PSingle(@data[0]),high(Data)+1);
  1504. end;
  1505. function popnvariance(const data : PSingle; Const N : Integer) : float;
  1506. begin
  1507. PopnVariance:=TotalVariance(Data,N)/N;
  1508. end;
  1509. procedure momentskewkurtosis(const data : array of single;
  1510. out m1,m2,m3,m4,skew,kurtosis : float); inline;
  1511. begin
  1512. momentskewkurtosis(PSingle(@Data[0]),High(Data)+1,m1,m2,m3,m4,skew,kurtosis);
  1513. end;
  1514. type
  1515. TMoments2to4 = array[2 .. 4] of float;
  1516. procedure momentskewkurtosis(
  1517. const data: pSingle;
  1518. Const N: integer;
  1519. out m1: float;
  1520. out m2: float;
  1521. out m3: float;
  1522. out m4: float;
  1523. out skew: float;
  1524. out kurtosis: float
  1525. );
  1526. procedure CalcDevSums2to4(data: PSingle; N: SizeInt; m1: float; out m2to4: TMoments2to4);
  1527. var
  1528. tm2, tm3, tm4, dev, dev2: float;
  1529. i: SizeInt;
  1530. m2to4Part0, m2to4Part1: TMoments2to4;
  1531. begin
  1532. if N >= RecursiveSumThreshold then
  1533. begin
  1534. CalcDevSums2to4(data, SizeUint(N) div 2, m1, m2to4Part0);
  1535. CalcDevSums2to4(data + SizeUint(N) div 2, N - SizeUint(N) div 2, m1, m2to4Part1);
  1536. for i := Low(TMoments2to4) to High(TMoments2to4) do
  1537. m2to4[i] := m2to4Part0[i] + m2to4Part1[i];
  1538. end
  1539. else
  1540. begin
  1541. tm2 := 0;
  1542. tm3 := 0;
  1543. tm4 := 0;
  1544. for i := 0 to N - 1 do
  1545. begin
  1546. dev := data[i] - m1;
  1547. dev2 := sqr(dev);
  1548. tm2 := tm2 + dev2;
  1549. tm3 := tm3 + dev2 * dev;
  1550. tm4 := tm4 + sqr(dev2);
  1551. end;
  1552. m2to4[2] := tm2;
  1553. m2to4[3] := tm3;
  1554. m2to4[4] := tm4;
  1555. end;
  1556. end;
  1557. var
  1558. reciprocalN: float;
  1559. m2to4: TMoments2to4;
  1560. begin
  1561. m1 := 0;
  1562. reciprocalN := 1/N;
  1563. m1 := reciprocalN * sum(data, N);
  1564. CalcDevSums2to4(data, N, m1, m2to4);
  1565. m2 := reciprocalN * m2to4[2];
  1566. m3 := reciprocalN * m2to4[3];
  1567. m4 := reciprocalN * m2to4[4];
  1568. skew := m3 / (sqrt(m2)*m2);
  1569. kurtosis := m4 / (m2 * m2);
  1570. end;
  1571. function norm(const data : array of Single) : float; inline;
  1572. begin
  1573. norm:=Norm(PSingle(@data[0]),High(Data)+1);
  1574. end;
  1575. function norm(const data : PSingle; Const N : Integer) : float;
  1576. begin
  1577. norm:=sqrt(sumofsquares(data,N));
  1578. end;
  1579. {$endif FPC_HAS_TYPE_SINGLE}
  1580. {$ifdef FPC_HAS_TYPE_DOUBLE}
  1581. procedure MeanAndTotalVariance
  1582. (const data: PDouble; N: LongInt; var mu, variance: float);
  1583. function CalcVariance(data: PDouble; N: SizeInt; mu: float): float;
  1584. var
  1585. i: SizeInt;
  1586. begin
  1587. if N>=RecursiveSumThreshold then
  1588. result:=CalcVariance(data,SizeUint(N) div 2,mu)+CalcVariance(data+SizeUint(N) div 2,N-SizeUint(N) div 2,mu)
  1589. else
  1590. begin
  1591. result:=0;
  1592. for i:=0 to N-1 do
  1593. result:=result+Sqr(data[i]-mu);
  1594. end;
  1595. end;
  1596. begin
  1597. mu := Mean( data, N );
  1598. variance := CalcVariance( data, N, mu );
  1599. end;
  1600. function stddev(const data : array of Double) : float; inline;
  1601. begin
  1602. Result:=Stddev(PDouble(@Data[0]),High(Data)+1)
  1603. end;
  1604. function stddev(const data : PDouble; Const N : Integer) : float;
  1605. begin
  1606. StdDev:=Sqrt(Variance(Data,N));
  1607. end;
  1608. procedure meanandstddev(const data : array of Double;
  1609. var mean,stddev : float);
  1610. begin
  1611. Meanandstddev(PDouble(@Data[0]),High(Data)+1,Mean,stddev);
  1612. end;
  1613. procedure meanandstddev
  1614. ( const data: PDouble;
  1615. const N: Longint;
  1616. var mean,
  1617. stdDev: Float
  1618. );
  1619. var totalVariance: float;
  1620. begin
  1621. MeanAndTotalVariance( data, N, mean, totalVariance );
  1622. if N < 2 then stdDev := 0
  1623. else stdDev := Sqrt( totalVariance / ( N - 1 ) );
  1624. end;
  1625. function variance(const data : array of Double) : float; inline;
  1626. begin
  1627. Variance:=Variance(PDouble(@Data[0]),High(Data)+1);
  1628. end;
  1629. function variance(const data : PDouble; Const N : Integer) : float;
  1630. begin
  1631. If N=1 then
  1632. Result:=0
  1633. else
  1634. Result:=TotalVariance(Data,N)/(N-1);
  1635. end;
  1636. function totalvariance(const data : array of Double) : float; inline;
  1637. begin
  1638. Result:=TotalVariance(PDouble(@Data[0]),High(Data)+1);
  1639. end;
  1640. function totalvariance(const data : PDouble; const N : Integer) : float;
  1641. var mu: float;
  1642. begin
  1643. MeanAndTotalVariance( data, N, mu, result );
  1644. end;
  1645. function popnstddev(const data : array of Double) : float;
  1646. begin
  1647. PopnStdDev:=Sqrt(PopnVariance(PDouble(@Data[0]),High(Data)+1));
  1648. end;
  1649. function popnstddev(const data : PDouble; Const N : Integer) : float;
  1650. begin
  1651. PopnStdDev:=Sqrt(PopnVariance(Data,N));
  1652. end;
  1653. function popnvariance(const data : array of Double) : float; inline;
  1654. begin
  1655. popnvariance:=popnvariance(PDouble(@data[0]),high(Data)+1);
  1656. end;
  1657. function popnvariance(const data : PDouble; Const N : Integer) : float;
  1658. begin
  1659. PopnVariance:=TotalVariance(Data,N)/N;
  1660. end;
  1661. procedure momentskewkurtosis(const data : array of Double;
  1662. out m1,m2,m3,m4,skew,kurtosis : float);
  1663. begin
  1664. momentskewkurtosis(PDouble(@Data[0]),High(Data)+1,m1,m2,m3,m4,skew,kurtosis);
  1665. end;
  1666. procedure momentskewkurtosis(
  1667. const data: pdouble;
  1668. Const N: integer;
  1669. out m1: float;
  1670. out m2: float;
  1671. out m3: float;
  1672. out m4: float;
  1673. out skew: float;
  1674. out kurtosis: float
  1675. );
  1676. procedure CalcDevSums2to4(data: PDouble; N: SizeInt; m1: float; out m2to4: TMoments2to4);
  1677. var
  1678. tm2, tm3, tm4, dev, dev2: float;
  1679. i: SizeInt;
  1680. m2to4Part0, m2to4Part1: TMoments2to4;
  1681. begin
  1682. if N >= RecursiveSumThreshold then
  1683. begin
  1684. CalcDevSums2to4(data, SizeUint(N) div 2, m1, m2to4Part0);
  1685. CalcDevSums2to4(data + SizeUint(N) div 2, N - SizeUint(N) div 2, m1, m2to4Part1);
  1686. for i := Low(TMoments2to4) to High(TMoments2to4) do
  1687. m2to4[i] := m2to4Part0[i] + m2to4Part1[i];
  1688. end
  1689. else
  1690. begin
  1691. tm2 := 0;
  1692. tm3 := 0;
  1693. tm4 := 0;
  1694. for i := 0 to N - 1 do
  1695. begin
  1696. dev := data[i] - m1;
  1697. dev2 := sqr(dev);
  1698. tm2 := tm2 + dev2;
  1699. tm3 := tm3 + dev2 * dev;
  1700. tm4 := tm4 + sqr(dev2);
  1701. end;
  1702. m2to4[2] := tm2;
  1703. m2to4[3] := tm3;
  1704. m2to4[4] := tm4;
  1705. end;
  1706. end;
  1707. var
  1708. reciprocalN: float;
  1709. m2to4: TMoments2to4;
  1710. begin
  1711. m1 := 0;
  1712. reciprocalN := 1/N;
  1713. m1 := reciprocalN * sum(data, N);
  1714. CalcDevSums2to4(data, N, m1, m2to4);
  1715. m2 := reciprocalN * m2to4[2];
  1716. m3 := reciprocalN * m2to4[3];
  1717. m4 := reciprocalN * m2to4[4];
  1718. skew := m3 / (sqrt(m2)*m2);
  1719. kurtosis := m4 / (m2 * m2);
  1720. end;
  1721. function norm(const data : array of Double) : float; inline;
  1722. begin
  1723. norm:=Norm(PDouble(@data[0]),High(Data)+1);
  1724. end;
  1725. function norm(const data : PDouble; Const N : Integer) : float;
  1726. begin
  1727. norm:=sqrt(sumofsquares(data,N));
  1728. end;
  1729. {$endif FPC_HAS_TYPE_DOUBLE}
  1730. {$ifdef FPC_HAS_TYPE_EXTENDED}
  1731. procedure MeanAndTotalVariance
  1732. (const data: PExtended; N: LongInt; var mu, variance: float);
  1733. function CalcVariance(data: PExtended; N: SizeInt; mu: float): float;
  1734. var
  1735. i: SizeInt;
  1736. begin
  1737. if N>=RecursiveSumThreshold then
  1738. result:=CalcVariance(data,SizeUint(N) div 2,mu)+CalcVariance(data+SizeUint(N) div 2,N-SizeUint(N) div 2,mu)
  1739. else
  1740. begin
  1741. result:=0;
  1742. for i:=0 to N-1 do
  1743. result:=result+Sqr(data[i]-mu);
  1744. end;
  1745. end;
  1746. begin
  1747. mu := Mean( data, N );
  1748. variance := CalcVariance( data, N, mu );
  1749. end;
  1750. function stddev(const data : array of Extended) : float; inline;
  1751. begin
  1752. Result:=Stddev(PExtended(@Data[0]),High(Data)+1)
  1753. end;
  1754. function stddev(const data : PExtended; Const N : Integer) : float;
  1755. begin
  1756. StdDev:=Sqrt(Variance(Data,N));
  1757. end;
  1758. procedure meanandstddev(const data : array of Extended;
  1759. var mean,stddev : float); inline;
  1760. begin
  1761. Meanandstddev(PExtended(@Data[0]),High(Data)+1,Mean,stddev);
  1762. end;
  1763. procedure meanandstddev
  1764. ( const data: PExtended;
  1765. const N: Longint;
  1766. var mean,
  1767. stdDev: Float
  1768. );
  1769. var totalVariance: float;
  1770. begin
  1771. MeanAndTotalVariance( data, N, mean, totalVariance );
  1772. if N < 2 then stdDev := 0
  1773. else stdDev := Sqrt( totalVariance / ( N - 1 ) );
  1774. end;
  1775. function variance(const data : array of Extended) : float; inline;
  1776. begin
  1777. Variance:=Variance(PExtended(@Data[0]),High(Data)+1);
  1778. end;
  1779. function variance(const data : PExtended; Const N : Integer) : float;
  1780. begin
  1781. If N=1 then
  1782. Result:=0
  1783. else
  1784. Result:=TotalVariance(Data,N)/(N-1);
  1785. end;
  1786. function totalvariance(const data : array of Extended) : float; inline;
  1787. begin
  1788. Result:=TotalVariance(PExtended(@Data[0]),High(Data)+1);
  1789. end;
  1790. function totalvariance(const data : PExtended;Const N : Integer) : float;
  1791. var mu: float;
  1792. begin
  1793. MeanAndTotalVariance( data, N, mu, result );
  1794. end;
  1795. function popnstddev(const data : array of Extended) : float;
  1796. begin
  1797. PopnStdDev:=Sqrt(PopnVariance(PExtended(@Data[0]),High(Data)+1));
  1798. end;
  1799. function popnstddev(const data : PExtended; Const N : Integer) : float;
  1800. begin
  1801. PopnStdDev:=Sqrt(PopnVariance(Data,N));
  1802. end;
  1803. function popnvariance(const data : array of Extended) : float; inline;
  1804. begin
  1805. popnvariance:=popnvariance(PExtended(@data[0]),high(Data)+1);
  1806. end;
  1807. function popnvariance(const data : PExtended; Const N : Integer) : float;
  1808. begin
  1809. PopnVariance:=TotalVariance(Data,N)/N;
  1810. end;
  1811. procedure momentskewkurtosis(const data : array of Extended;
  1812. out m1,m2,m3,m4,skew,kurtosis : float); inline;
  1813. begin
  1814. momentskewkurtosis(PExtended(@Data[0]),High(Data)+1,m1,m2,m3,m4,skew,kurtosis);
  1815. end;
  1816. procedure momentskewkurtosis(
  1817. const data: pExtended;
  1818. Const N: Integer;
  1819. out m1: float;
  1820. out m2: float;
  1821. out m3: float;
  1822. out m4: float;
  1823. out skew: float;
  1824. out kurtosis: float
  1825. );
  1826. procedure CalcDevSums2to4(data: PExtended; N: SizeInt; m1: float; out m2to4: TMoments2to4);
  1827. var
  1828. tm2, tm3, tm4, dev, dev2: float;
  1829. i: SizeInt;
  1830. m2to4Part0, m2to4Part1: TMoments2to4;
  1831. begin
  1832. if N >= RecursiveSumThreshold then
  1833. begin
  1834. CalcDevSums2to4(data, SizeUint(N) div 2, m1, m2to4Part0);
  1835. CalcDevSums2to4(data + SizeUint(N) div 2, N - SizeUint(N) div 2, m1, m2to4Part1);
  1836. for i := Low(TMoments2to4) to High(TMoments2to4) do
  1837. m2to4[i] := m2to4Part0[i] + m2to4Part1[i];
  1838. end
  1839. else
  1840. begin
  1841. tm2 := 0;
  1842. tm3 := 0;
  1843. tm4 := 0;
  1844. for i := 0 to N - 1 do
  1845. begin
  1846. dev := data[i] - m1;
  1847. dev2 := sqr(dev);
  1848. tm2 := tm2 + dev2;
  1849. tm3 := tm3 + dev2 * dev;
  1850. tm4 := tm4 + sqr(dev2);
  1851. end;
  1852. m2to4[2] := tm2;
  1853. m2to4[3] := tm3;
  1854. m2to4[4] := tm4;
  1855. end;
  1856. end;
  1857. var
  1858. reciprocalN: float;
  1859. m2to4: TMoments2to4;
  1860. begin
  1861. m1 := 0;
  1862. reciprocalN := 1/N;
  1863. m1 := reciprocalN * sum(data, N);
  1864. CalcDevSums2to4(data, N, m1, m2to4);
  1865. m2 := reciprocalN * m2to4[2];
  1866. m3 := reciprocalN * m2to4[3];
  1867. m4 := reciprocalN * m2to4[4];
  1868. skew := m3 / (sqrt(m2)*m2);
  1869. kurtosis := m4 / (m2 * m2);
  1870. end;
  1871. function norm(const data : array of Extended) : float; inline;
  1872. begin
  1873. norm:=Norm(PExtended(@data[0]),High(Data)+1);
  1874. end;
  1875. function norm(const data : PExtended; Const N : Integer) : float;
  1876. begin
  1877. norm:=sqrt(sumofsquares(data,N));
  1878. end;
  1879. {$endif FPC_HAS_TYPE_EXTENDED}
  1880. function MinIntValue(const Data: array of Integer): Integer;
  1881. var
  1882. I: SizeInt;
  1883. begin
  1884. Result := Data[Low(Data)];
  1885. For I := Succ(Low(Data)) To High(Data) Do
  1886. If Data[I] < Result Then Result := Data[I];
  1887. end;
  1888. function MaxIntValue(const Data: array of Integer): Integer;
  1889. var
  1890. I: SizeInt;
  1891. begin
  1892. Result := Data[Low(Data)];
  1893. For I := Succ(Low(Data)) To High(Data) Do
  1894. If Data[I] > Result Then Result := Data[I];
  1895. end;
  1896. function MinValue(const Data: array of Integer): Integer; inline;
  1897. begin
  1898. Result:=MinValue(Pinteger(@Data[0]),High(Data)+1)
  1899. end;
  1900. function MinValue(const Data: PInteger; Const N : Integer): Integer;
  1901. var
  1902. I: SizeInt;
  1903. begin
  1904. Result := Data[0];
  1905. For I := 1 To N-1 do
  1906. If Data[I] < Result Then Result := Data[I];
  1907. end;
  1908. function MaxValue(const Data: array of Integer): Integer; inline;
  1909. begin
  1910. Result:=MaxValue(PInteger(@Data[0]),High(Data)+1)
  1911. end;
  1912. function maxvalue(const data : PInteger; Const N : Integer) : Integer;
  1913. var
  1914. i : SizeInt;
  1915. begin
  1916. { get an initial value }
  1917. maxvalue:=data[0];
  1918. for i:=1 to N-1 do
  1919. if data[i]>maxvalue then
  1920. maxvalue:=data[i];
  1921. end;
  1922. {$ifdef FPC_HAS_TYPE_SINGLE}
  1923. function minvalue(const data : array of Single) : Single; inline;
  1924. begin
  1925. Result:=minvalue(PSingle(@data[0]),High(Data)+1);
  1926. end;
  1927. function minvalue(const data : PSingle; Const N : Integer) : Single;
  1928. var
  1929. i : SizeInt;
  1930. begin
  1931. { get an initial value }
  1932. minvalue:=data[0];
  1933. for i:=1 to N-1 do
  1934. if data[i]<minvalue then
  1935. minvalue:=data[i];
  1936. end;
  1937. function maxvalue(const data : array of Single) : Single; inline;
  1938. begin
  1939. Result:=maxvalue(PSingle(@data[0]),High(Data)+1);
  1940. end;
  1941. function maxvalue(const data : PSingle; Const N : Integer) : Single;
  1942. var
  1943. i : SizeInt;
  1944. begin
  1945. { get an initial value }
  1946. maxvalue:=data[0];
  1947. for i:=1 to N-1 do
  1948. if data[i]>maxvalue then
  1949. maxvalue:=data[i];
  1950. end;
  1951. {$endif FPC_HAS_TYPE_SINGLE}
  1952. {$ifdef FPC_HAS_TYPE_DOUBLE}
  1953. function minvalue(const data : array of Double) : Double; inline;
  1954. begin
  1955. Result:=minvalue(PDouble(@data[0]),High(Data)+1);
  1956. end;
  1957. function minvalue(const data : PDouble; Const N : Integer) : Double;
  1958. var
  1959. i : SizeInt;
  1960. begin
  1961. { get an initial value }
  1962. minvalue:=data[0];
  1963. for i:=1 to N-1 do
  1964. if data[i]<minvalue then
  1965. minvalue:=data[i];
  1966. end;
  1967. function maxvalue(const data : array of Double) : Double; inline;
  1968. begin
  1969. Result:=maxvalue(PDouble(@data[0]),High(Data)+1);
  1970. end;
  1971. function maxvalue(const data : PDouble; Const N : Integer) : Double;
  1972. var
  1973. i : SizeInt;
  1974. begin
  1975. { get an initial value }
  1976. maxvalue:=data[0];
  1977. for i:=1 to N-1 do
  1978. if data[i]>maxvalue then
  1979. maxvalue:=data[i];
  1980. end;
  1981. {$endif FPC_HAS_TYPE_DOUBLE}
  1982. {$ifdef FPC_HAS_TYPE_EXTENDED}
  1983. function minvalue(const data : array of Extended) : Extended; inline;
  1984. begin
  1985. Result:=minvalue(PExtended(@data[0]),High(Data)+1);
  1986. end;
  1987. function minvalue(const data : PExtended; Const N : Integer) : Extended;
  1988. var
  1989. i : SizeInt;
  1990. begin
  1991. { get an initial value }
  1992. minvalue:=data[0];
  1993. for i:=1 to N-1 do
  1994. if data[i]<minvalue then
  1995. minvalue:=data[i];
  1996. end;
  1997. function maxvalue(const data : array of Extended) : Extended; inline;
  1998. begin
  1999. Result:=maxvalue(PExtended(@data[0]),High(Data)+1);
  2000. end;
  2001. function maxvalue(const data : PExtended; Const N : Integer) : Extended;
  2002. var
  2003. i : SizeInt;
  2004. begin
  2005. { get an initial value }
  2006. maxvalue:=data[0];
  2007. for i:=1 to N-1 do
  2008. if data[i]>maxvalue then
  2009. maxvalue:=data[i];
  2010. end;
  2011. {$endif FPC_HAS_TYPE_EXTENDED}
  2012. function Min(a, b: Integer): Integer;inline;
  2013. begin
  2014. if a < b then
  2015. Result := a
  2016. else
  2017. Result := b;
  2018. end;
  2019. function Max(a, b: Integer): Integer;inline;
  2020. begin
  2021. if a > b then
  2022. Result := a
  2023. else
  2024. Result := b;
  2025. end;
  2026. {
  2027. function Min(a, b: Cardinal): Cardinal;inline;
  2028. begin
  2029. if a < b then
  2030. Result := a
  2031. else
  2032. Result := b;
  2033. end;
  2034. function Max(a, b: Cardinal): Cardinal;inline;
  2035. begin
  2036. if a > b then
  2037. Result := a
  2038. else
  2039. Result := b;
  2040. end;
  2041. }
  2042. function Min(a, b: Int64): Int64;inline;
  2043. begin
  2044. if a < b then
  2045. Result := a
  2046. else
  2047. Result := b;
  2048. end;
  2049. function Max(a, b: Int64): Int64;inline;
  2050. begin
  2051. if a > b then
  2052. Result := a
  2053. else
  2054. Result := b;
  2055. end;
  2056. function Min(a, b: QWord): QWord; inline;
  2057. begin
  2058. if a < b then
  2059. Result := a
  2060. else
  2061. Result := b;
  2062. end;
  2063. function Max(a, b: QWord): Qword;inline;
  2064. begin
  2065. if a > b then
  2066. Result := a
  2067. else
  2068. Result := b;
  2069. end;
  2070. {$ifdef FPC_HAS_TYPE_SINGLE}
  2071. function Min(a, b: Single): Single;inline;
  2072. begin
  2073. if a < b then
  2074. Result := a
  2075. else
  2076. Result := b;
  2077. end;
  2078. function Max(a, b: Single): Single;inline;
  2079. begin
  2080. if a > b then
  2081. Result := a
  2082. else
  2083. Result := b;
  2084. end;
  2085. {$endif FPC_HAS_TYPE_SINGLE}
  2086. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2087. function Min(a, b: Double): Double;inline;
  2088. begin
  2089. if a < b then
  2090. Result := a
  2091. else
  2092. Result := b;
  2093. end;
  2094. function Max(a, b: Double): Double;inline;
  2095. begin
  2096. if a > b then
  2097. Result := a
  2098. else
  2099. Result := b;
  2100. end;
  2101. {$endif FPC_HAS_TYPE_DOUBLE}
  2102. {$ifdef FPC_HAS_TYPE_EXTENDED}
  2103. function Min(a, b: Extended): Extended;inline;
  2104. begin
  2105. if a < b then
  2106. Result := a
  2107. else
  2108. Result := b;
  2109. end;
  2110. function Max(a, b: Extended): Extended;inline;
  2111. begin
  2112. if a > b then
  2113. Result := a
  2114. else
  2115. Result := b;
  2116. end;
  2117. {$endif FPC_HAS_TYPE_EXTENDED}
  2118. function InRange(const AValue, AMin, AMax: Integer): Boolean;inline;
  2119. begin
  2120. Result:=(AValue>=AMin) and (AValue<=AMax);
  2121. end;
  2122. function InRange(const AValue, AMin, AMax: Int64): Boolean;inline;
  2123. begin
  2124. Result:=(AValue>=AMin) and (AValue<=AMax);
  2125. end;
  2126. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2127. function InRange(const AValue, AMin, AMax: Double): Boolean;inline;
  2128. begin
  2129. Result:=(AValue>=AMin) and (AValue<=AMax);
  2130. end;
  2131. {$endif FPC_HAS_TYPE_DOUBLE}
  2132. function EnsureRange(const AValue, AMin, AMax: Integer): Integer;inline;
  2133. begin
  2134. Result:=AValue;
  2135. If Result<AMin then
  2136. Result:=AMin;
  2137. if Result>AMax then
  2138. Result:=AMax;
  2139. end;
  2140. function EnsureRange(const AValue, AMin, AMax: Int64): Int64;inline;
  2141. begin
  2142. Result:=AValue;
  2143. If Result<AMin then
  2144. Result:=AMin;
  2145. if Result>AMax then
  2146. Result:=AMax;
  2147. end;
  2148. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2149. function EnsureRange(const AValue, AMin, AMax: Double): Double;inline;
  2150. begin
  2151. Result:=AValue;
  2152. If Result<AMin then
  2153. Result:=AMin;
  2154. if Result>AMax then
  2155. Result:=AMax;
  2156. end;
  2157. {$endif FPC_HAS_TYPE_DOUBLE}
  2158. Const
  2159. EZeroResolution = Extended(1E-16);
  2160. DZeroResolution = Double(1E-12);
  2161. SZeroResolution = Single(1E-4);
  2162. function IsZero(const A: Single; Epsilon: Single): Boolean;
  2163. begin
  2164. if (Epsilon=0) then
  2165. Epsilon:=SZeroResolution;
  2166. Result:=Abs(A)<=Epsilon;
  2167. end;
  2168. function IsZero(const A: Single): Boolean;inline;
  2169. begin
  2170. Result:=IsZero(A,single(SZeroResolution));
  2171. end;
  2172. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2173. function IsZero(const A: Double; Epsilon: Double): Boolean;
  2174. begin
  2175. if (Epsilon=0) then
  2176. Epsilon:=DZeroResolution;
  2177. Result:=Abs(A)<=Epsilon;
  2178. end;
  2179. function IsZero(const A: Double): Boolean;inline;
  2180. begin
  2181. Result:=IsZero(A,DZeroResolution);
  2182. end;
  2183. {$endif FPC_HAS_TYPE_DOUBLE}
  2184. {$ifdef FPC_HAS_TYPE_EXTENDED}
  2185. function IsZero(const A: Extended; Epsilon: Extended): Boolean;
  2186. begin
  2187. if (Epsilon=0) then
  2188. Epsilon:=EZeroResolution;
  2189. Result:=Abs(A)<=Epsilon;
  2190. end;
  2191. function IsZero(const A: Extended): Boolean;inline;
  2192. begin
  2193. Result:=IsZero(A,EZeroResolution);
  2194. end;
  2195. {$endif FPC_HAS_TYPE_EXTENDED}
  2196. type
  2197. TSplitDouble = packed record
  2198. cards: Array[0..1] of cardinal;
  2199. end;
  2200. TSplitExtended = packed record
  2201. cards: Array[0..1] of cardinal;
  2202. w: word;
  2203. end;
  2204. function IsNan(const d : Single): Boolean; overload;
  2205. begin
  2206. result:=(longword(d) and $7fffffff)>$7f800000;
  2207. end;
  2208. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2209. function IsNan(const d : Double): Boolean;
  2210. var
  2211. fraczero, expMaximal: boolean;
  2212. begin
  2213. {$if defined(FPC_BIG_ENDIAN) or defined(FPC_DOUBLE_HILO_SWAPPED)}
  2214. expMaximal := ((TSplitDouble(d).cards[0] shr 20) and $7ff) = 2047;
  2215. fraczero:= (TSplitDouble(d).cards[0] and $fffff = 0) and
  2216. (TSplitDouble(d).cards[1] = 0);
  2217. {$else FPC_BIG_ENDIAN}
  2218. expMaximal := ((TSplitDouble(d).cards[1] shr 20) and $7ff) = 2047;
  2219. fraczero := (TSplitDouble(d).cards[1] and $fffff = 0) and
  2220. (TSplitDouble(d).cards[0] = 0);
  2221. {$endif FPC_BIG_ENDIAN}
  2222. Result:=expMaximal and not(fraczero);
  2223. end;
  2224. {$endif FPC_HAS_TYPE_DOUBLE}
  2225. {$ifdef FPC_HAS_TYPE_EXTENDED}
  2226. function IsNan(const d : Extended): Boolean; overload;
  2227. var
  2228. fraczero, expMaximal: boolean;
  2229. begin
  2230. {$ifdef FPC_BIG_ENDIAN}
  2231. {$error no support for big endian extended type yet}
  2232. {$else FPC_BIG_ENDIAN}
  2233. expMaximal := (TSplitExtended(d).w and $7fff) = 32767;
  2234. fraczero := (TSplitExtended(d).cards[0] = 0) and
  2235. ((TSplitExtended(d).cards[1] and $7fffffff) = 0);
  2236. {$endif FPC_BIG_ENDIAN}
  2237. Result:=expMaximal and not(fraczero);
  2238. end;
  2239. {$endif FPC_HAS_TYPE_EXTENDED}
  2240. function IsInfinite(const d : Single): Boolean; overload;
  2241. begin
  2242. result:=(longword(d) and $7fffffff)=$7f800000;
  2243. end;
  2244. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2245. function IsInfinite(const d : Double): Boolean; overload;
  2246. var
  2247. fraczero, expMaximal: boolean;
  2248. begin
  2249. {$if defined(FPC_BIG_ENDIAN) or defined(FPC_DOUBLE_HILO_SWAPPED)}
  2250. expMaximal := ((TSplitDouble(d).cards[0] shr 20) and $7ff) = 2047;
  2251. fraczero:= (TSplitDouble(d).cards[0] and $fffff = 0) and
  2252. (TSplitDouble(d).cards[1] = 0);
  2253. {$else FPC_BIG_ENDIAN}
  2254. expMaximal := ((TSplitDouble(d).cards[1] shr 20) and $7ff) = 2047;
  2255. fraczero := (TSplitDouble(d).cards[1] and $fffff = 0) and
  2256. (TSplitDouble(d).cards[0] = 0);
  2257. {$endif FPC_BIG_ENDIAN}
  2258. Result:=expMaximal and fraczero;
  2259. end;
  2260. {$endif FPC_HAS_TYPE_DOUBLE}
  2261. {$ifdef FPC_HAS_TYPE_EXTENDED}
  2262. function IsInfinite(const d : Extended): Boolean; overload;
  2263. var
  2264. fraczero, expMaximal: boolean;
  2265. begin
  2266. {$ifdef FPC_BIG_ENDIAN}
  2267. {$error no support for big endian extended type yet}
  2268. {$else FPC_BIG_ENDIAN}
  2269. expMaximal := (TSplitExtended(d).w and $7fff) = 32767;
  2270. fraczero := (TSplitExtended(d).cards[0] = 0) and
  2271. ((TSplitExtended(d).cards[1] and $7fffffff) = 0);
  2272. {$endif FPC_BIG_ENDIAN}
  2273. Result:=expMaximal and fraczero;
  2274. end;
  2275. {$endif FPC_HAS_TYPE_EXTENDED}
  2276. function copysign(x,y: float): float;
  2277. begin
  2278. {$if defined(FPC_HAS_TYPE_FLOAT128)}
  2279. {$error copysign not yet implemented for float128}
  2280. {$elseif defined(FPC_HAS_TYPE_EXTENDED)}
  2281. TSplitExtended(x).w:=(TSplitExtended(x).w and $7fff) or (TSplitExtended(y).w and $8000);
  2282. {$elseif defined(FPC_HAS_TYPE_DOUBLE)}
  2283. {$if defined(FPC_BIG_ENDIAN) or defined(FPC_DOUBLE_HILO_SWAPPED)}
  2284. TSplitDouble(x).cards[0]:=(TSplitDouble(x).cards[0] and $7fffffff) or (TSplitDouble(y).cards[0] and longword($80000000));
  2285. {$else}
  2286. TSplitDouble(x).cards[1]:=(TSplitDouble(x).cards[1] and $7fffffff) or (TSplitDouble(y).cards[1] and longword($80000000));
  2287. {$endif}
  2288. {$else}
  2289. longword(x):=longword(x and $7fffffff) or (longword(y) and longword($80000000));
  2290. {$endif}
  2291. result:=x;
  2292. end;
  2293. {$ifdef FPC_HAS_TYPE_EXTENDED}
  2294. function SameValue(const A, B: Extended; Epsilon: Extended): Boolean;
  2295. begin
  2296. if (Epsilon=0) then
  2297. Epsilon:=Max(Min(Abs(A),Abs(B))*EZeroResolution,EZeroResolution);
  2298. if (A>B) then
  2299. Result:=((A-B)<=Epsilon)
  2300. else
  2301. Result:=((B-A)<=Epsilon);
  2302. end;
  2303. function SameValue(const A, B: Extended): Boolean;inline;
  2304. begin
  2305. Result:=SameValue(A,B,0.0);
  2306. end;
  2307. {$endif FPC_HAS_TYPE_EXTENDED}
  2308. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2309. function SameValue(const A, B: Double): Boolean;inline;
  2310. begin
  2311. Result:=SameValue(A,B,0.0);
  2312. end;
  2313. function SameValue(const A, B: Double; Epsilon: Double): Boolean;
  2314. begin
  2315. if (Epsilon=0) then
  2316. Epsilon:=Max(Min(Abs(A),Abs(B))*DZeroResolution,DZeroResolution);
  2317. if (A>B) then
  2318. Result:=((A-B)<=Epsilon)
  2319. else
  2320. Result:=((B-A)<=Epsilon);
  2321. end;
  2322. {$endif FPC_HAS_TYPE_DOUBLE}
  2323. function SameValue(const A, B: Single): Boolean;inline;
  2324. begin
  2325. Result:=SameValue(A,B,0);
  2326. end;
  2327. function SameValue(const A, B: Single; Epsilon: Single): Boolean;
  2328. begin
  2329. if (Epsilon=0) then
  2330. Epsilon:=Max(Min(Abs(A),Abs(B))*SZeroResolution,SZeroResolution);
  2331. if (A>B) then
  2332. Result:=((A-B)<=Epsilon)
  2333. else
  2334. Result:=((B-A)<=Epsilon);
  2335. end;
  2336. // Some CPUs probably allow a faster way of doing this in a single operation...
  2337. // There weshould define FPC_MATH_HAS_CPUDIVMOD in the header mathuh.inc and implement it using asm.
  2338. {$ifndef FPC_MATH_HAS_DIVMOD}
  2339. procedure DivMod(Dividend: LongInt; Divisor: Word; var Result, Remainder: Word);
  2340. begin
  2341. if Dividend < 0 then
  2342. begin
  2343. { Use DivMod with >=0 dividend }
  2344. Dividend:=-Dividend;
  2345. { The documented behavior of Pascal's div/mod operators and DivMod
  2346. on negative dividends is to return Result closer to zero and
  2347. a negative Remainder. Which means that we can just negate both
  2348. Result and Remainder, and all it's Ok. }
  2349. Result:=-(Dividend Div Divisor);
  2350. Remainder:=-(Dividend+(Result*Divisor));
  2351. end
  2352. else
  2353. begin
  2354. Result:=Dividend Div Divisor;
  2355. Remainder:=Dividend-(Result*Divisor);
  2356. end;
  2357. end;
  2358. procedure DivMod(Dividend: LongInt; Divisor: Word; var Result, Remainder: SmallInt);
  2359. begin
  2360. if Dividend < 0 then
  2361. begin
  2362. { Use DivMod with >=0 dividend }
  2363. Dividend:=-Dividend;
  2364. { The documented behavior of Pascal's div/mod operators and DivMod
  2365. on negative dividends is to return Result closer to zero and
  2366. a negative Remainder. Which means that we can just negate both
  2367. Result and Remainder, and all it's Ok. }
  2368. Result:=-(Dividend Div Divisor);
  2369. Remainder:=-(Dividend+(Result*Divisor));
  2370. end
  2371. else
  2372. begin
  2373. Result:=Dividend Div Divisor;
  2374. Remainder:=Dividend-(Result*Divisor);
  2375. end;
  2376. end;
  2377. procedure DivMod(Dividend: DWord; Divisor: DWord; var Result, Remainder: DWord);
  2378. begin
  2379. Result:=Dividend Div Divisor;
  2380. Remainder:=Dividend-(Result*Divisor);
  2381. end;
  2382. procedure DivMod(Dividend: LongInt; Divisor: LongInt; var Result, Remainder: LongInt);
  2383. begin
  2384. if Dividend < 0 then
  2385. begin
  2386. { Use DivMod with >=0 dividend }
  2387. Dividend:=-Dividend;
  2388. { The documented behavior of Pascal's div/mod operators and DivMod
  2389. on negative dividends is to return Result closer to zero and
  2390. a negative Remainder. Which means that we can just negate both
  2391. Result and Remainder, and all it's Ok. }
  2392. Result:=-(Dividend Div Divisor);
  2393. Remainder:=-(Dividend+(Result*Divisor));
  2394. end
  2395. else
  2396. begin
  2397. Result:=Dividend Div Divisor;
  2398. Remainder:=Dividend-(Result*Divisor);
  2399. end;
  2400. end;
  2401. {$endif FPC_MATH_HAS_DIVMOD}
  2402. { Floating point modulo}
  2403. {$ifdef FPC_HAS_TYPE_SINGLE}
  2404. function FMod(const a, b: Single): Single;inline;overload;
  2405. begin
  2406. result:= a-b * Int(a/b);
  2407. end;
  2408. {$endif FPC_HAS_TYPE_SINGLE}
  2409. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2410. function FMod(const a, b: Double): Double;inline;overload;
  2411. begin
  2412. result:= a-b * Int(a/b);
  2413. end;
  2414. {$endif FPC_HAS_TYPE_DOUBLE}
  2415. {$ifdef FPC_HAS_TYPE_EXTENDED}
  2416. function FMod(const a, b: Extended): Extended;inline;overload;
  2417. begin
  2418. result:= a-b * Int(a/b);
  2419. end;
  2420. {$endif FPC_HAS_TYPE_EXTENDED}
  2421. operator mod(const a,b:float) c:float;inline;
  2422. begin
  2423. c:= a-b * Int(a/b);
  2424. if SameValue(abs(c),abs(b)) then
  2425. c:=0.0;
  2426. end;
  2427. function ifthen(val:boolean;const iftrue:integer; const iffalse:integer= 0) :integer;
  2428. begin
  2429. if val then result:=iftrue else result:=iffalse;
  2430. end;
  2431. function ifthen(val:boolean;const iftrue:int64 ; const iffalse:int64 = 0) :int64;
  2432. begin
  2433. if val then result:=iftrue else result:=iffalse;
  2434. end;
  2435. function ifthen(val:boolean;const iftrue:double ; const iffalse:double =0.0):double;
  2436. begin
  2437. if val then result:=iftrue else result:=iffalse;
  2438. end;
  2439. // dilemma here. asm can do the two comparisons in one go?
  2440. // but pascal is portable and can be inlined. Ah well, we need purepascal's anyway:
  2441. function CompareValue(const A, B : Integer): TValueRelationship;
  2442. begin
  2443. result:=GreaterThanValue;
  2444. if a=b then
  2445. result:=EqualsValue
  2446. else
  2447. if a<b then
  2448. result:=LessThanValue;
  2449. end;
  2450. function CompareValue(const A, B: Int64): TValueRelationship;
  2451. begin
  2452. result:=GreaterThanValue;
  2453. if a=b then
  2454. result:=EqualsValue
  2455. else
  2456. if a<b then
  2457. result:=LessThanValue;
  2458. end;
  2459. function CompareValue(const A, B: QWord): TValueRelationship;
  2460. begin
  2461. result:=GreaterThanValue;
  2462. if a=b then
  2463. result:=EqualsValue
  2464. else
  2465. if a<b then
  2466. result:=LessThanValue;
  2467. end;
  2468. {$ifdef FPC_HAS_TYPE_SINGLE}
  2469. function CompareValue(const A, B: Single; delta: Single = 0.0): TValueRelationship;
  2470. begin
  2471. result:=GreaterThanValue;
  2472. if abs(a-b)<=delta then
  2473. result:=EqualsValue
  2474. else
  2475. if a<b then
  2476. result:=LessThanValue;
  2477. end;
  2478. {$endif}
  2479. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2480. function CompareValue(const A, B: Double; delta: Double = 0.0): TValueRelationship;
  2481. begin
  2482. result:=GreaterThanValue;
  2483. if abs(a-b)<=delta then
  2484. result:=EqualsValue
  2485. else
  2486. if a<b then
  2487. result:=LessThanValue;
  2488. end;
  2489. {$endif}
  2490. {$ifdef FPC_HAS_TYPE_EXTENDED}
  2491. function CompareValue (const A, B: Extended; delta: Extended = 0.0): TValueRelationship;
  2492. begin
  2493. result:=GreaterThanValue;
  2494. if abs(a-b)<=delta then
  2495. result:=EqualsValue
  2496. else
  2497. if a<b then
  2498. result:=LessThanValue;
  2499. end;
  2500. {$endif}
  2501. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2502. function RoundTo(const AValue: Double; const Digits: TRoundToRange): Double;
  2503. var
  2504. RV : Double;
  2505. begin
  2506. RV:=IntPower(10,Digits);
  2507. Result:=Round(AValue/RV)*RV;
  2508. end;
  2509. {$endif}
  2510. {$ifdef FPC_HAS_TYPE_EXTENDED}
  2511. function RoundTo(const AVAlue: Extended; const Digits: TRoundToRange): Extended;
  2512. var
  2513. RV : Extended;
  2514. begin
  2515. RV:=IntPower(10,Digits);
  2516. Result:=Round(AValue/RV)*RV;
  2517. end;
  2518. {$endif}
  2519. {$ifdef FPC_HAS_TYPE_SINGLE}
  2520. function RoundTo(const AValue: Single; const Digits: TRoundToRange): Single;
  2521. var
  2522. RV : Single;
  2523. begin
  2524. RV:=IntPower(10,Digits);
  2525. Result:=Round(AValue/RV)*RV;
  2526. end;
  2527. {$endif}
  2528. {$ifdef FPC_HAS_TYPE_SINGLE}
  2529. function SimpleRoundTo(const AValue: Single; const Digits: TRoundToRange = -2): Single;
  2530. var
  2531. RV : Single;
  2532. begin
  2533. RV := IntPower(10, -Digits);
  2534. if AValue < 0 then
  2535. Result := Int((AValue*RV) - 0.5)/RV
  2536. else
  2537. Result := Int((AValue*RV) + 0.5)/RV;
  2538. end;
  2539. {$endif}
  2540. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2541. function SimpleRoundTo(const AValue: Double; const Digits: TRoundToRange = -2): Double;
  2542. var
  2543. RV : Double;
  2544. begin
  2545. RV := IntPower(10, -Digits);
  2546. if AValue < 0 then
  2547. Result := Int((AValue*RV) - 0.5)/RV
  2548. else
  2549. Result := Int((AValue*RV) + 0.5)/RV;
  2550. end;
  2551. {$endif}
  2552. {$ifdef FPC_HAS_TYPE_EXTENDED}
  2553. function SimpleRoundTo(const AValue: Extended; const Digits: TRoundToRange = -2): Extended;
  2554. var
  2555. RV : Extended;
  2556. begin
  2557. RV := IntPower(10, -Digits);
  2558. if AValue < 0 then
  2559. Result := Int((AValue*RV) - 0.5)/RV
  2560. else
  2561. Result := Int((AValue*RV) + 0.5)/RV;
  2562. end;
  2563. {$endif}
  2564. function RandomFrom(const AValues: array of Double): Double; overload;
  2565. begin
  2566. result:=AValues[random(High(AValues)+1)];
  2567. end;
  2568. function RandomFrom(const AValues: array of Integer): Integer; overload;
  2569. begin
  2570. result:=AValues[random(High(AValues)+1)];
  2571. end;
  2572. function RandomFrom(const AValues: array of Int64): Int64; overload;
  2573. begin
  2574. result:=AValues[random(High(AValues)+1)];
  2575. end;
  2576. {$if FPC_FULLVERSION >=30101}
  2577. generic function RandomFrom<T>(const AValues:array of T):T;
  2578. begin
  2579. result:=AValues[random(High(AValues)+1)];
  2580. end;
  2581. {$endif}
  2582. function FutureValue(ARate: Float; NPeriods: Integer;
  2583. APayment, APresentValue: Float; APaymentTime: TPaymentTime): Float;
  2584. var
  2585. q, qn, factor: Float;
  2586. begin
  2587. if ARate = 0 then
  2588. Result := -APresentValue - APayment * NPeriods
  2589. else begin
  2590. q := 1.0 + ARate;
  2591. qn := power(q, NPeriods);
  2592. factor := (qn - 1) / (q - 1);
  2593. if APaymentTime = ptStartOfPeriod then
  2594. factor := factor * q;
  2595. Result := -(APresentValue * qn + APayment*factor);
  2596. end;
  2597. end;
  2598. function InterestRate(NPeriods: Integer; APayment, APresentValue, AFutureValue: Float;
  2599. APaymentTime: TPaymentTime): Float;
  2600. { The interest rate cannot be calculated analytically. We solve the equation
  2601. numerically by means of the Newton method:
  2602. - guess value for the interest reate
  2603. - calculate at which interest rate the tangent of the curve fv(rate)
  2604. (straight line!) has the requested future vale.
  2605. - use this rate for the next iteration. }
  2606. const
  2607. DELTA = 0.001;
  2608. EPS = 1E-9; // required precision of interest rate (after typ. 6 iterations)
  2609. MAXIT = 20; // max iteration count to protect agains non-convergence
  2610. var
  2611. r1, r2, dr: Float;
  2612. fv1, fv2: Float;
  2613. iteration: Integer;
  2614. begin
  2615. iteration := 0;
  2616. r1 := 0.05; // inital guess
  2617. repeat
  2618. r2 := r1 + DELTA;
  2619. fv1 := FutureValue(r1, NPeriods, APayment, APresentValue, APaymentTime);
  2620. fv2 := FutureValue(r2, NPeriods, APayment, APresentValue, APaymentTime);
  2621. dr := (AFutureValue - fv1) / (fv2 - fv1) * delta; // tangent at fv(r)
  2622. r1 := r1 + dr; // next guess
  2623. inc(iteration);
  2624. until (abs(dr) < EPS) or (iteration >= MAXIT);
  2625. Result := r1;
  2626. end;
  2627. function NumberOfPeriods(ARate, APayment, APresentValue, AFutureValue: Float;
  2628. APaymentTime: TPaymentTime): Float;
  2629. { Solve the cash flow equation (1) for q^n and take the logarithm }
  2630. var
  2631. q, x1, x2: Float;
  2632. begin
  2633. if ARate = 0 then
  2634. Result := -(APresentValue + AFutureValue) / APayment
  2635. else begin
  2636. q := 1.0 + ARate;
  2637. if APaymentTime = ptStartOfPeriod then
  2638. APayment := APayment * q;
  2639. x1 := APayment - AFutureValue * ARate;
  2640. x2 := APayment + APresentValue * ARate;
  2641. if (x2 = 0) // we have to divide by x2
  2642. or (sign(x1) * sign(x2) < 0) // the argument of the log is negative
  2643. then
  2644. Result := Infinity
  2645. else begin
  2646. Result := ln(x1/x2) / ln(q);
  2647. end;
  2648. end;
  2649. end;
  2650. function Payment(ARate: Float; NPeriods: Integer;
  2651. APresentValue, AFutureValue: Float; APaymentTime: TPaymentTime): Float;
  2652. var
  2653. q, qn, factor: Float;
  2654. begin
  2655. if ARate = 0 then
  2656. Result := -(AFutureValue + APresentValue) / NPeriods
  2657. else begin
  2658. q := 1.0 + ARate;
  2659. qn := power(q, NPeriods);
  2660. factor := (qn - 1) / (q - 1);
  2661. if APaymentTime = ptStartOfPeriod then
  2662. factor := factor * q;
  2663. Result := -(AFutureValue + APresentValue * qn) / factor;
  2664. end;
  2665. end;
  2666. function PresentValue(ARate: Float; NPeriods: Integer;
  2667. APayment, AFutureValue: Float; APaymentTime: TPaymentTime): Float;
  2668. var
  2669. q, qn, factor: Float;
  2670. begin
  2671. if ARate = 0.0 then
  2672. Result := -AFutureValue - APayment * NPeriods
  2673. else begin
  2674. q := 1.0 + ARate;
  2675. qn := power(q, NPeriods);
  2676. factor := (qn - 1) / (q - 1);
  2677. if APaymentTime = ptStartOfPeriod then
  2678. factor := factor * q;
  2679. Result := -(AFutureValue + APayment*factor) / qn;
  2680. end;
  2681. end;
  2682. {$else}
  2683. implementation
  2684. {$endif FPUNONE}
  2685. end.