math.pp 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162
  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;const exponent : Integer) : 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;const exponent : Integer) : float;
  881. var
  882. i : longint;
  883. begin
  884. if (base = 0.0) and (exponent = 0) then
  885. result:=1
  886. else
  887. begin
  888. if exponent<0 then
  889. base:=1.0/base;
  890. i:=abs(exponent);
  891. intpower:=1.0;
  892. while i>0 do
  893. begin
  894. while (i and 1)=0 do
  895. begin
  896. i:=i shr 1;
  897. base:=sqr(base);
  898. end;
  899. i:=i-1;
  900. intpower:=intpower*base;
  901. end;
  902. end;
  903. end;
  904. operator ** (bas,expo : float) e: float; inline;
  905. begin
  906. e:=power(bas,expo);
  907. end;
  908. operator ** (bas,expo : int64) i: int64; inline;
  909. begin
  910. i:=round(intpower(bas,expo));
  911. end;
  912. function ceil(x : float) : integer;
  913. begin
  914. Result:=Trunc(x)+ord(Frac(x)>0);
  915. end;
  916. function ceil64(x: float): Int64;
  917. begin
  918. Result:=Trunc(x)+ord(Frac(x)>0);
  919. end;
  920. function floor(x : float) : integer;
  921. begin
  922. Result:=Trunc(x)-ord(Frac(x)<0);
  923. end;
  924. function floor64(x: float): Int64;
  925. begin
  926. Result:=Trunc(x)-ord(Frac(x)<0);
  927. end;
  928. // Correction for "rounding to nearest, ties to even".
  929. // RoundToNearestTieToEven(QWE.RTYUIOP) = QWE + TieToEven(ER, TYUIOP <> 0).
  930. function TieToEven(AB: cardinal; somethingAfter: boolean): cardinal;
  931. begin
  932. result := AB and 1;
  933. if (result <> 0) and not somethingAfter then
  934. result := AB shr 1;
  935. end;
  936. {$ifdef FPC_HAS_TYPE_SINGLE}
  937. procedure Frexp(X: single; out Mantissa: single; out Exponent: integer);
  938. var
  939. M: uint32;
  940. E, ExtraE: int32;
  941. begin
  942. Mantissa := X;
  943. E := TSingleRec(X).Exp;
  944. if (E > 0) and (E < 2 * TSingleRec.Bias + 1) then
  945. begin
  946. // Normal.
  947. TSingleRec(Mantissa).Exp := TSingleRec.Bias - 1;
  948. Exponent := E - (TSingleRec.Bias - 1);
  949. exit;
  950. end;
  951. if E = 0 then
  952. begin
  953. M := TSingleRec(X).Frac;
  954. if M <> 0 then
  955. begin
  956. // Subnormal.
  957. ExtraE := 23 - BsrDWord(M);
  958. TSingleRec(Mantissa).Frac := M shl ExtraE; // "and (1 shl 23 - 1)" required to remove starting 1, but .SetFrac already does it.
  959. TSingleRec(Mantissa).Exp := TSingleRec.Bias - 1;
  960. Exponent := -TSingleRec.Bias + 2 - ExtraE;
  961. exit;
  962. end;
  963. end;
  964. // ±0, ±Inf, NaN.
  965. Exponent := 0;
  966. end;
  967. function Ldexp(X: single; p: integer): single;
  968. var
  969. M, E: uint32;
  970. xp, sh: integer;
  971. begin
  972. E := TSingleRec(X).Exp;
  973. if (E = 0) and (TSingleRec(X).Frac = 0) or (E = 2 * TSingleRec.Bias + 1) then
  974. // ±0, ±Inf, NaN.
  975. exit(X);
  976. Frexp(X, result, xp);
  977. inc(xp, p);
  978. if (xp >= -TSingleRec.Bias + 2) and (xp <= TSingleRec.Bias + 1) then
  979. // Normalized.
  980. TSingleRec(result).Exp := xp + (TSingleRec.Bias - 1)
  981. else if xp > TSingleRec.Bias + 1 then
  982. begin
  983. // Overflow.
  984. TSingleRec(result).Exp := 2 * TSingleRec.Bias + 1;
  985. TSingleRec(result).Frac := 0;
  986. end else
  987. begin
  988. TSingleRec(result).Exp := 0;
  989. if xp >= -TSingleRec.Bias + 2 - 23 then
  990. begin
  991. // Denormalized.
  992. M := TSingleRec(result).Frac or uint32(1) shl 23;
  993. sh := -TSingleRec.Bias + 1 - xp;
  994. TSingleRec(result).Frac := M shr (sh + 1) + TieToEven(M shr sh and 3, M and (uint32(1) shl sh - 1) <> 0);
  995. end else
  996. // Underflow.
  997. TSingleRec(result).Frac := 0;
  998. end;
  999. end;
  1000. {$endif}
  1001. {$ifdef FPC_HAS_TYPE_DOUBLE}
  1002. procedure Frexp(X: double; out Mantissa: double; out Exponent: integer);
  1003. var
  1004. M: uint64;
  1005. E, ExtraE: int32;
  1006. begin
  1007. Mantissa := X;
  1008. E := TDoubleRec(X).Exp;
  1009. if (E > 0) and (E < 2 * TDoubleRec.Bias + 1) then
  1010. begin
  1011. // Normal.
  1012. TDoubleRec(Mantissa).Exp := TDoubleRec.Bias - 1;
  1013. Exponent := E - (TDoubleRec.Bias - 1);
  1014. exit;
  1015. end;
  1016. if E = 0 then
  1017. begin
  1018. M := TDoubleRec(X).Frac;
  1019. if M <> 0 then
  1020. begin
  1021. // Subnormal.
  1022. ExtraE := 52 - BsrQWord(M);
  1023. TDoubleRec(Mantissa).Frac := M shl ExtraE; // "and (1 shl 52 - 1)" required to remove starting 1, but .SetFrac already does it.
  1024. TDoubleRec(Mantissa).Exp := TDoubleRec.Bias - 1;
  1025. Exponent := -TDoubleRec.Bias + 2 - ExtraE;
  1026. exit;
  1027. end;
  1028. end;
  1029. // ±0, ±Inf, NaN.
  1030. Exponent := 0;
  1031. end;
  1032. function Ldexp(X: double; p: integer): double;
  1033. var
  1034. M: uint64;
  1035. E: uint32;
  1036. xp, sh: integer;
  1037. begin
  1038. E := TDoubleRec(X).Exp;
  1039. if (E = 0) and (TDoubleRec(X).Frac = 0) or (E = 2 * TDoubleRec.Bias + 1) then
  1040. // ±0, ±Inf, NaN.
  1041. exit(X);
  1042. Frexp(X, result, xp);
  1043. inc(xp, p);
  1044. if (xp >= -TDoubleRec.Bias + 2) and (xp <= TDoubleRec.Bias + 1) then
  1045. // Normalized.
  1046. TDoubleRec(result).Exp := xp + (TDoubleRec.Bias - 1)
  1047. else if xp > TDoubleRec.Bias + 1 then
  1048. begin
  1049. // Overflow.
  1050. TDoubleRec(result).Exp := 2 * TDoubleRec.Bias + 1;
  1051. TDoubleRec(result).Frac := 0;
  1052. end else
  1053. begin
  1054. TDoubleRec(result).Exp := 0;
  1055. if xp >= -TDoubleRec.Bias + 2 - 52 then
  1056. begin
  1057. // Denormalized.
  1058. M := TDoubleRec(result).Frac or uint64(1) shl 52;
  1059. sh := -TSingleRec.Bias + 1 - xp;
  1060. TDoubleRec(result).Frac := M shr (sh + 1) + TieToEven(M shr sh and 3, M and (uint64(1) shl sh - 1) <> 0);
  1061. end else
  1062. // Underflow.
  1063. TDoubleRec(result).Frac := 0;
  1064. end;
  1065. end;
  1066. {$endif}
  1067. {$ifdef FPC_HAS_TYPE_EXTENDED}
  1068. procedure Frexp(X: extended; out Mantissa: extended; out Exponent: integer);
  1069. var
  1070. M: uint64;
  1071. E, ExtraE: int32;
  1072. begin
  1073. Mantissa := X;
  1074. E := TExtended80Rec(X).Exp;
  1075. if (E > 0) and (E < 2 * TExtended80Rec.Bias + 1) then
  1076. begin
  1077. // Normal.
  1078. TExtended80Rec(Mantissa).Exp := TExtended80Rec.Bias - 1;
  1079. Exponent := E - (TExtended80Rec.Bias - 1);
  1080. exit;
  1081. end;
  1082. if E = 0 then
  1083. begin
  1084. M := TExtended80Rec(X).Frac;
  1085. if M <> 0 then
  1086. begin
  1087. // Subnormal. Extended has explicit starting 1.
  1088. ExtraE := 63 - BsrQWord(TExtended80Rec(X).Frac);
  1089. TExtended80Rec(Mantissa).Frac := M shl ExtraE;
  1090. TExtended80Rec(Mantissa).Exp := TExtended80Rec.Bias - 1;
  1091. Exponent := -TExtended80Rec.Bias + 2 - ExtraE;
  1092. exit;
  1093. end;
  1094. end;
  1095. // ±0, ±Inf, NaN.
  1096. Exponent := 0;
  1097. end;
  1098. function Ldexp(X: extended; p: integer): extended;
  1099. var
  1100. M: uint64;
  1101. E: uint32;
  1102. xp, sh: integer;
  1103. begin
  1104. E := TExtended80Rec(X).Exp;
  1105. if (E = 0) and (TExtended80Rec(X).Frac = 0) or (E = 2 * TExtended80Rec.Bias + 1) then
  1106. // ±0, ±Inf, NaN.
  1107. exit(X);
  1108. Frexp(X, result, xp);
  1109. inc(xp, p);
  1110. if (xp >= -TExtended80Rec.Bias + 2) and (xp <= TExtended80Rec.Bias + 1) then
  1111. // Normalized.
  1112. TExtended80Rec(result).Exp := xp + (TExtended80Rec.Bias - 1)
  1113. else if xp > TExtended80Rec.Bias + 1 then
  1114. begin
  1115. // Overflow.
  1116. TExtended80Rec(result).Exp := 2 * TExtended80Rec.Bias + 1;
  1117. TExtended80Rec(result).Frac := uint64(1) shl 63;
  1118. end else
  1119. begin
  1120. TExtended80Rec(result).Exp := 0;
  1121. if xp >= -TExtended80Rec.Bias + 2 - 63 then
  1122. begin
  1123. // Denormalized.
  1124. M := TExtended80Rec(result).Frac;
  1125. sh := -TExtended80Rec.Bias + 1 - xp;
  1126. TExtended80Rec(result).Frac := M shr (sh + 1) + TieToEven(M shr sh and 3, M and (uint64(1) shl sh - 1) <> 0);
  1127. end else
  1128. // Underflow.
  1129. TExtended80Rec(result).Frac := 0;
  1130. end;
  1131. end;
  1132. {$endif}
  1133. const
  1134. { Cutoff for https://en.wikipedia.org/wiki/Pairwise_summation; sums of at least this many elements are split in two halves. }
  1135. RecursiveSumThreshold=12;
  1136. {$ifdef FPC_HAS_TYPE_SINGLE}
  1137. function mean(const data : array of Single) : float;
  1138. begin
  1139. Result:=Mean(PSingle(@data[0]),High(Data)+1);
  1140. end;
  1141. function mean(const data : PSingle; Const N : longint) : float;
  1142. begin
  1143. mean:=sum(Data,N);
  1144. mean:=mean/N;
  1145. end;
  1146. function sum(const data : array of Single) : float;inline;
  1147. begin
  1148. Result:=Sum(PSingle(@Data[0]),High(Data)+1);
  1149. end;
  1150. function sum(const data : PSingle;Const N : longint) : float;
  1151. var
  1152. i : SizeInt;
  1153. begin
  1154. if N>=RecursiveSumThreshold then
  1155. result:=sum(data,longword(N) div 2)+sum(data+longword(N) div 2,N-longword(N) div 2)
  1156. else
  1157. begin
  1158. result:=0;
  1159. for i:=0 to N-1 do
  1160. result:=result+data[i];
  1161. end;
  1162. end;
  1163. {$endif FPC_HAS_TYPE_SINGLE}
  1164. {$ifdef FPC_HAS_TYPE_DOUBLE}
  1165. function mean(const data : array of Double) : float; inline;
  1166. begin
  1167. Result:=Mean(PDouble(@data[0]),High(Data)+1);
  1168. end;
  1169. function mean(const data : PDouble; Const N : longint) : float;
  1170. begin
  1171. mean:=sum(Data,N);
  1172. mean:=mean/N;
  1173. end;
  1174. function sum(const data : array of Double) : float; inline;
  1175. begin
  1176. Result:=Sum(PDouble(@Data[0]),High(Data)+1);
  1177. end;
  1178. function sum(const data : PDouble;Const N : longint) : float;
  1179. var
  1180. i : SizeInt;
  1181. begin
  1182. if N>=RecursiveSumThreshold then
  1183. result:=sum(data,longword(N) div 2)+sum(data+longword(N) div 2,N-longword(N) div 2)
  1184. else
  1185. begin
  1186. result:=0;
  1187. for i:=0 to N-1 do
  1188. result:=result+data[i];
  1189. end;
  1190. end;
  1191. {$endif FPC_HAS_TYPE_DOUBLE}
  1192. {$ifdef FPC_HAS_TYPE_EXTENDED}
  1193. function mean(const data : array of Extended) : float;
  1194. begin
  1195. Result:=Mean(PExtended(@data[0]),High(Data)+1);
  1196. end;
  1197. function mean(const data : PExtended; Const N : longint) : float;
  1198. begin
  1199. mean:=sum(Data,N);
  1200. mean:=mean/N;
  1201. end;
  1202. function sum(const data : array of Extended) : float; inline;
  1203. begin
  1204. Result:=Sum(PExtended(@Data[0]),High(Data)+1);
  1205. end;
  1206. function sum(const data : PExtended;Const N : longint) : float;
  1207. var
  1208. i : SizeInt;
  1209. begin
  1210. if N>=RecursiveSumThreshold then
  1211. result:=sum(data,longword(N) div 2)+sum(data+longword(N) div 2,N-longword(N) div 2)
  1212. else
  1213. begin
  1214. result:=0;
  1215. for i:=0 to N-1 do
  1216. result:=result+data[i];
  1217. end;
  1218. end;
  1219. {$endif FPC_HAS_TYPE_EXTENDED}
  1220. function sumInt(const data : PInt64;Const N : longint) : Int64;
  1221. var
  1222. i : SizeInt;
  1223. begin
  1224. sumInt:=0;
  1225. for i:=0 to N-1 do
  1226. sumInt:=sumInt+data[i];
  1227. end;
  1228. function sumInt(const data : array of Int64) : Int64; inline;
  1229. begin
  1230. Result:=SumInt(PInt64(@Data[0]),High(Data)+1);
  1231. end;
  1232. function mean(const data : PInt64; const N : Longint):Float;
  1233. begin
  1234. mean:=sumInt(Data,N);
  1235. mean:=mean/N;
  1236. end;
  1237. function mean(const data: array of Int64):Float;
  1238. begin
  1239. mean:=mean(PInt64(@data[0]),High(Data)+1);
  1240. end;
  1241. function sumInt(const data : PInteger; Const N : longint) : Int64;
  1242. var
  1243. i : SizeInt;
  1244. begin
  1245. sumInt:=0;
  1246. for i:=0 to N-1 do
  1247. sumInt:=sumInt+data[i];
  1248. end;
  1249. function sumInt(const data : array of Integer) : Int64;inline;
  1250. begin
  1251. Result:=sumInt(PInteger(@Data[0]),High(Data)+1);
  1252. end;
  1253. function mean(const data : PInteger; const N : Longint):Float;
  1254. begin
  1255. mean:=sumInt(Data,N);
  1256. mean:=mean/N;
  1257. end;
  1258. function mean(const data: array of Integer):Float;
  1259. begin
  1260. mean:=mean(PInteger(@data[0]),High(Data)+1);
  1261. end;
  1262. {$ifdef FPC_HAS_TYPE_SINGLE}
  1263. function sumofsquares(const data : array of Single) : float; inline;
  1264. begin
  1265. Result:=sumofsquares(PSingle(@data[0]),High(Data)+1);
  1266. end;
  1267. function sumofsquares(const data : PSingle; Const N : Integer) : float;
  1268. var
  1269. i : SizeInt;
  1270. begin
  1271. if N>=RecursiveSumThreshold then
  1272. result:=sumofsquares(data,cardinal(N) div 2)+sumofsquares(data+cardinal(N) div 2,N-cardinal(N) div 2)
  1273. else
  1274. begin
  1275. result:=0;
  1276. for i:=0 to N-1 do
  1277. result:=result+sqr(data[i]);
  1278. end;
  1279. end;
  1280. procedure sumsandsquares(const data : array of Single;
  1281. var sum,sumofsquares : float); inline;
  1282. begin
  1283. sumsandsquares (PSingle(@Data[0]),High(Data)+1,Sum,sumofsquares);
  1284. end;
  1285. procedure sumsandsquares(const data : PSingle; Const N : Integer;
  1286. var sum,sumofsquares : float);
  1287. var
  1288. i : SizeInt;
  1289. temp,tsum,tsumofsquares,sum0,sumofsquares0,sum1,sumofsquares1 : float;
  1290. begin
  1291. if N>=RecursiveSumThreshold then
  1292. begin
  1293. sumsandsquares(data,cardinal(N) div 2,sum0,sumofsquares0);
  1294. sumsandsquares(data+cardinal(N) div 2,N-cardinal(N) div 2,sum1,sumofsquares1);
  1295. sum:=sum0+sum1;
  1296. sumofsquares:=sumofsquares0+sumofsquares1;
  1297. end
  1298. else
  1299. begin
  1300. tsum:=0;
  1301. tsumofsquares:=0;
  1302. for i:=0 to N-1 do
  1303. begin
  1304. temp:=data[i];
  1305. tsum:=tsum+temp;
  1306. tsumofsquares:=tsumofsquares+sqr(temp);
  1307. end;
  1308. sum:=tsum;
  1309. sumofsquares:=tsumofsquares;
  1310. end;
  1311. end;
  1312. {$endif FPC_HAS_TYPE_SINGLE}
  1313. {$ifdef FPC_HAS_TYPE_DOUBLE}
  1314. function sumofsquares(const data : array of Double) : float; inline;
  1315. begin
  1316. Result:=sumofsquares(PDouble(@data[0]),High(Data)+1);
  1317. end;
  1318. function sumofsquares(const data : PDouble; Const N : Integer) : float;
  1319. var
  1320. i : SizeInt;
  1321. begin
  1322. if N>=RecursiveSumThreshold then
  1323. result:=sumofsquares(data,cardinal(N) div 2)+sumofsquares(data+cardinal(N) div 2,N-cardinal(N) div 2)
  1324. else
  1325. begin
  1326. result:=0;
  1327. for i:=0 to N-1 do
  1328. result:=result+sqr(data[i]);
  1329. end;
  1330. end;
  1331. procedure sumsandsquares(const data : array of Double;
  1332. var sum,sumofsquares : float);
  1333. begin
  1334. sumsandsquares (PDouble(@Data[0]),High(Data)+1,Sum,sumofsquares);
  1335. end;
  1336. procedure sumsandsquares(const data : PDouble; Const N : Integer;
  1337. var sum,sumofsquares : float);
  1338. var
  1339. i : SizeInt;
  1340. temp,tsum,tsumofsquares,sum0,sumofsquares0,sum1,sumofsquares1 : float;
  1341. begin
  1342. if N>=RecursiveSumThreshold then
  1343. begin
  1344. sumsandsquares(data,cardinal(N) div 2,sum0,sumofsquares0);
  1345. sumsandsquares(data+cardinal(N) div 2,N-cardinal(N) div 2,sum1,sumofsquares1);
  1346. sum:=sum0+sum1;
  1347. sumofsquares:=sumofsquares0+sumofsquares1;
  1348. end
  1349. else
  1350. begin
  1351. tsum:=0;
  1352. tsumofsquares:=0;
  1353. for i:=0 to N-1 do
  1354. begin
  1355. temp:=data[i];
  1356. tsum:=tsum+temp;
  1357. tsumofsquares:=tsumofsquares+sqr(temp);
  1358. end;
  1359. sum:=tsum;
  1360. sumofsquares:=tsumofsquares;
  1361. end;
  1362. end;
  1363. {$endif FPC_HAS_TYPE_DOUBLE}
  1364. {$ifdef FPC_HAS_TYPE_EXTENDED}
  1365. function sumofsquares(const data : array of Extended) : float; inline;
  1366. begin
  1367. Result:=sumofsquares(PExtended(@data[0]),High(Data)+1);
  1368. end;
  1369. function sumofsquares(const data : PExtended; Const N : Integer) : float;
  1370. var
  1371. i : SizeInt;
  1372. begin
  1373. if N>=RecursiveSumThreshold then
  1374. result:=sumofsquares(data,cardinal(N) div 2)+sumofsquares(data+cardinal(N) div 2,N-cardinal(N) div 2)
  1375. else
  1376. begin
  1377. result:=0;
  1378. for i:=0 to N-1 do
  1379. result:=result+sqr(data[i]);
  1380. end;
  1381. end;
  1382. procedure sumsandsquares(const data : array of Extended;
  1383. var sum,sumofsquares : float); inline;
  1384. begin
  1385. sumsandsquares (PExtended(@Data[0]),High(Data)+1,Sum,sumofsquares);
  1386. end;
  1387. procedure sumsandsquares(const data : PExtended; Const N : Integer;
  1388. var sum,sumofsquares : float);
  1389. var
  1390. i : SizeInt;
  1391. temp,tsum,tsumofsquares,sum0,sumofsquares0,sum1,sumofsquares1 : float;
  1392. begin
  1393. if N>=RecursiveSumThreshold then
  1394. begin
  1395. sumsandsquares(data,cardinal(N) div 2,sum0,sumofsquares0);
  1396. sumsandsquares(data+cardinal(N) div 2,N-cardinal(N) div 2,sum1,sumofsquares1);
  1397. sum:=sum0+sum1;
  1398. sumofsquares:=sumofsquares0+sumofsquares1;
  1399. end
  1400. else
  1401. begin
  1402. tsum:=0;
  1403. tsumofsquares:=0;
  1404. for i:=0 to N-1 do
  1405. begin
  1406. temp:=data[i];
  1407. tsum:=tsum+temp;
  1408. tsumofsquares:=tsumofsquares+sqr(temp);
  1409. end;
  1410. sum:=tsum;
  1411. sumofsquares:=tsumofsquares;
  1412. end;
  1413. end;
  1414. {$endif FPC_HAS_TYPE_EXTENDED}
  1415. function randg(mean,stddev : float) : float;
  1416. Var U1,S2 : Float;
  1417. begin
  1418. repeat
  1419. u1:= 2*random-1;
  1420. S2:=Sqr(U1)+sqr(2*random-1);
  1421. until s2<1;
  1422. randg:=Sqrt(-2*ln(S2)/S2)*u1*stddev+Mean;
  1423. end;
  1424. function RandomRange(const aFrom, aTo: Integer): Integer;
  1425. begin
  1426. Result:=Random(Abs(aFrom-aTo))+Min(aTo,AFrom);
  1427. end;
  1428. function RandomRange(const aFrom, aTo: Int64): Int64;
  1429. begin
  1430. Result:=Random(Abs(aFrom-aTo))+Min(aTo,AFrom);
  1431. end;
  1432. {$ifdef FPC_HAS_TYPE_SINGLE}
  1433. procedure MeanAndTotalVariance
  1434. (const data: PSingle; N: LongInt; var mu, variance: float);
  1435. function CalcVariance(data: PSingle; N: SizeInt; mu: float): float;
  1436. var
  1437. i: SizeInt;
  1438. begin
  1439. if N>=RecursiveSumThreshold then
  1440. result:=CalcVariance(data,SizeUint(N) div 2,mu)+CalcVariance(data+SizeUint(N) div 2,N-SizeUint(N) div 2,mu)
  1441. else
  1442. begin
  1443. result:=0;
  1444. for i:=0 to N-1 do
  1445. result:=result+Sqr(data[i]-mu);
  1446. end;
  1447. end;
  1448. begin
  1449. mu := Mean( data, N );
  1450. variance := CalcVariance( data, N, mu );
  1451. end;
  1452. function stddev(const data : array of Single) : float; inline;
  1453. begin
  1454. Result:=Stddev(PSingle(@Data[0]),High(Data)+1);
  1455. end;
  1456. function stddev(const data : PSingle; Const N : Integer) : float;
  1457. begin
  1458. StdDev:=Sqrt(Variance(Data,N));
  1459. end;
  1460. procedure meanandstddev(const data : array of Single;
  1461. var mean,stddev : float); inline;
  1462. begin
  1463. Meanandstddev(PSingle(@Data[0]),High(Data)+1,Mean,stddev);
  1464. end;
  1465. procedure meanandstddev
  1466. ( const data: PSingle;
  1467. const N: Longint;
  1468. var mean,
  1469. stdDev: Float
  1470. );
  1471. var totalVariance: float;
  1472. begin
  1473. MeanAndTotalVariance( data, N, mean, totalVariance );
  1474. if N < 2 then stdDev := 0
  1475. else stdDev := Sqrt( totalVariance / ( N - 1 ) );
  1476. end;
  1477. function variance(const data : array of Single) : float; inline;
  1478. begin
  1479. Variance:=Variance(PSingle(@Data[0]),High(Data)+1);
  1480. end;
  1481. function variance(const data : PSingle; Const N : Integer) : float;
  1482. begin
  1483. If N=1 then
  1484. Result:=0
  1485. else
  1486. Result:=TotalVariance(Data,N)/(N-1);
  1487. end;
  1488. function totalvariance(const data : array of Single) : float; inline;
  1489. begin
  1490. Result:=TotalVariance(PSingle(@Data[0]),High(Data)+1);
  1491. end;
  1492. function totalvariance(const data : PSingle; const N : Integer) : float;
  1493. var mu: float;
  1494. begin
  1495. MeanAndTotalVariance( data, N, mu, result );
  1496. end;
  1497. function popnstddev(const data : array of Single) : float;
  1498. begin
  1499. PopnStdDev:=Sqrt(PopnVariance(PSingle(@Data[0]),High(Data)+1));
  1500. end;
  1501. function popnstddev(const data : PSingle; Const N : Integer) : float;
  1502. begin
  1503. PopnStdDev:=Sqrt(PopnVariance(Data,N));
  1504. end;
  1505. function popnvariance(const data : array of Single) : float; inline;
  1506. begin
  1507. popnvariance:=popnvariance(PSingle(@data[0]),high(Data)+1);
  1508. end;
  1509. function popnvariance(const data : PSingle; Const N : Integer) : float;
  1510. begin
  1511. PopnVariance:=TotalVariance(Data,N)/N;
  1512. end;
  1513. procedure momentskewkurtosis(const data : array of single;
  1514. out m1,m2,m3,m4,skew,kurtosis : float); inline;
  1515. begin
  1516. momentskewkurtosis(PSingle(@Data[0]),High(Data)+1,m1,m2,m3,m4,skew,kurtosis);
  1517. end;
  1518. type
  1519. TMoments2to4 = array[2 .. 4] of float;
  1520. procedure momentskewkurtosis(
  1521. const data: pSingle;
  1522. Const N: integer;
  1523. out m1: float;
  1524. out m2: float;
  1525. out m3: float;
  1526. out m4: float;
  1527. out skew: float;
  1528. out kurtosis: float
  1529. );
  1530. procedure CalcDevSums2to4(data: PSingle; N: SizeInt; m1: float; out m2to4: TMoments2to4);
  1531. var
  1532. tm2, tm3, tm4, dev, dev2: float;
  1533. i: SizeInt;
  1534. m2to4Part0, m2to4Part1: TMoments2to4;
  1535. begin
  1536. if N >= RecursiveSumThreshold then
  1537. begin
  1538. CalcDevSums2to4(data, SizeUint(N) div 2, m1, m2to4Part0);
  1539. CalcDevSums2to4(data + SizeUint(N) div 2, N - SizeUint(N) div 2, m1, m2to4Part1);
  1540. for i := Low(TMoments2to4) to High(TMoments2to4) do
  1541. m2to4[i] := m2to4Part0[i] + m2to4Part1[i];
  1542. end
  1543. else
  1544. begin
  1545. tm2 := 0;
  1546. tm3 := 0;
  1547. tm4 := 0;
  1548. for i := 0 to N - 1 do
  1549. begin
  1550. dev := data[i] - m1;
  1551. dev2 := sqr(dev);
  1552. tm2 := tm2 + dev2;
  1553. tm3 := tm3 + dev2 * dev;
  1554. tm4 := tm4 + sqr(dev2);
  1555. end;
  1556. m2to4[2] := tm2;
  1557. m2to4[3] := tm3;
  1558. m2to4[4] := tm4;
  1559. end;
  1560. end;
  1561. var
  1562. reciprocalN: float;
  1563. m2to4: TMoments2to4;
  1564. begin
  1565. m1 := 0;
  1566. reciprocalN := 1/N;
  1567. m1 := reciprocalN * sum(data, N);
  1568. CalcDevSums2to4(data, N, m1, m2to4);
  1569. m2 := reciprocalN * m2to4[2];
  1570. m3 := reciprocalN * m2to4[3];
  1571. m4 := reciprocalN * m2to4[4];
  1572. skew := m3 / (sqrt(m2)*m2);
  1573. kurtosis := m4 / (m2 * m2);
  1574. end;
  1575. function norm(const data : array of Single) : float; inline;
  1576. begin
  1577. norm:=Norm(PSingle(@data[0]),High(Data)+1);
  1578. end;
  1579. function norm(const data : PSingle; Const N : Integer) : float;
  1580. begin
  1581. norm:=sqrt(sumofsquares(data,N));
  1582. end;
  1583. {$endif FPC_HAS_TYPE_SINGLE}
  1584. {$ifdef FPC_HAS_TYPE_DOUBLE}
  1585. procedure MeanAndTotalVariance
  1586. (const data: PDouble; N: LongInt; var mu, variance: float);
  1587. function CalcVariance(data: PDouble; N: SizeInt; mu: float): float;
  1588. var
  1589. i: SizeInt;
  1590. begin
  1591. if N>=RecursiveSumThreshold then
  1592. result:=CalcVariance(data,SizeUint(N) div 2,mu)+CalcVariance(data+SizeUint(N) div 2,N-SizeUint(N) div 2,mu)
  1593. else
  1594. begin
  1595. result:=0;
  1596. for i:=0 to N-1 do
  1597. result:=result+Sqr(data[i]-mu);
  1598. end;
  1599. end;
  1600. begin
  1601. mu := Mean( data, N );
  1602. variance := CalcVariance( data, N, mu );
  1603. end;
  1604. function stddev(const data : array of Double) : float; inline;
  1605. begin
  1606. Result:=Stddev(PDouble(@Data[0]),High(Data)+1)
  1607. end;
  1608. function stddev(const data : PDouble; Const N : Integer) : float;
  1609. begin
  1610. StdDev:=Sqrt(Variance(Data,N));
  1611. end;
  1612. procedure meanandstddev(const data : array of Double;
  1613. var mean,stddev : float);
  1614. begin
  1615. Meanandstddev(PDouble(@Data[0]),High(Data)+1,Mean,stddev);
  1616. end;
  1617. procedure meanandstddev
  1618. ( const data: PDouble;
  1619. const N: Longint;
  1620. var mean,
  1621. stdDev: Float
  1622. );
  1623. var totalVariance: float;
  1624. begin
  1625. MeanAndTotalVariance( data, N, mean, totalVariance );
  1626. if N < 2 then stdDev := 0
  1627. else stdDev := Sqrt( totalVariance / ( N - 1 ) );
  1628. end;
  1629. function variance(const data : array of Double) : float; inline;
  1630. begin
  1631. Variance:=Variance(PDouble(@Data[0]),High(Data)+1);
  1632. end;
  1633. function variance(const data : PDouble; Const N : Integer) : float;
  1634. begin
  1635. If N=1 then
  1636. Result:=0
  1637. else
  1638. Result:=TotalVariance(Data,N)/(N-1);
  1639. end;
  1640. function totalvariance(const data : array of Double) : float; inline;
  1641. begin
  1642. Result:=TotalVariance(PDouble(@Data[0]),High(Data)+1);
  1643. end;
  1644. function totalvariance(const data : PDouble; const N : Integer) : float;
  1645. var mu: float;
  1646. begin
  1647. MeanAndTotalVariance( data, N, mu, result );
  1648. end;
  1649. function popnstddev(const data : array of Double) : float;
  1650. begin
  1651. PopnStdDev:=Sqrt(PopnVariance(PDouble(@Data[0]),High(Data)+1));
  1652. end;
  1653. function popnstddev(const data : PDouble; Const N : Integer) : float;
  1654. begin
  1655. PopnStdDev:=Sqrt(PopnVariance(Data,N));
  1656. end;
  1657. function popnvariance(const data : array of Double) : float; inline;
  1658. begin
  1659. popnvariance:=popnvariance(PDouble(@data[0]),high(Data)+1);
  1660. end;
  1661. function popnvariance(const data : PDouble; Const N : Integer) : float;
  1662. begin
  1663. PopnVariance:=TotalVariance(Data,N)/N;
  1664. end;
  1665. procedure momentskewkurtosis(const data : array of Double;
  1666. out m1,m2,m3,m4,skew,kurtosis : float);
  1667. begin
  1668. momentskewkurtosis(PDouble(@Data[0]),High(Data)+1,m1,m2,m3,m4,skew,kurtosis);
  1669. end;
  1670. procedure momentskewkurtosis(
  1671. const data: pdouble;
  1672. Const N: integer;
  1673. out m1: float;
  1674. out m2: float;
  1675. out m3: float;
  1676. out m4: float;
  1677. out skew: float;
  1678. out kurtosis: float
  1679. );
  1680. procedure CalcDevSums2to4(data: PDouble; N: SizeInt; m1: float; out m2to4: TMoments2to4);
  1681. var
  1682. tm2, tm3, tm4, dev, dev2: float;
  1683. i: SizeInt;
  1684. m2to4Part0, m2to4Part1: TMoments2to4;
  1685. begin
  1686. if N >= RecursiveSumThreshold then
  1687. begin
  1688. CalcDevSums2to4(data, SizeUint(N) div 2, m1, m2to4Part0);
  1689. CalcDevSums2to4(data + SizeUint(N) div 2, N - SizeUint(N) div 2, m1, m2to4Part1);
  1690. for i := Low(TMoments2to4) to High(TMoments2to4) do
  1691. m2to4[i] := m2to4Part0[i] + m2to4Part1[i];
  1692. end
  1693. else
  1694. begin
  1695. tm2 := 0;
  1696. tm3 := 0;
  1697. tm4 := 0;
  1698. for i := 0 to N - 1 do
  1699. begin
  1700. dev := data[i] - m1;
  1701. dev2 := sqr(dev);
  1702. tm2 := tm2 + dev2;
  1703. tm3 := tm3 + dev2 * dev;
  1704. tm4 := tm4 + sqr(dev2);
  1705. end;
  1706. m2to4[2] := tm2;
  1707. m2to4[3] := tm3;
  1708. m2to4[4] := tm4;
  1709. end;
  1710. end;
  1711. var
  1712. reciprocalN: float;
  1713. m2to4: TMoments2to4;
  1714. begin
  1715. m1 := 0;
  1716. reciprocalN := 1/N;
  1717. m1 := reciprocalN * sum(data, N);
  1718. CalcDevSums2to4(data, N, m1, m2to4);
  1719. m2 := reciprocalN * m2to4[2];
  1720. m3 := reciprocalN * m2to4[3];
  1721. m4 := reciprocalN * m2to4[4];
  1722. skew := m3 / (sqrt(m2)*m2);
  1723. kurtosis := m4 / (m2 * m2);
  1724. end;
  1725. function norm(const data : array of Double) : float; inline;
  1726. begin
  1727. norm:=Norm(PDouble(@data[0]),High(Data)+1);
  1728. end;
  1729. function norm(const data : PDouble; Const N : Integer) : float;
  1730. begin
  1731. norm:=sqrt(sumofsquares(data,N));
  1732. end;
  1733. {$endif FPC_HAS_TYPE_DOUBLE}
  1734. {$ifdef FPC_HAS_TYPE_EXTENDED}
  1735. procedure MeanAndTotalVariance
  1736. (const data: PExtended; N: LongInt; var mu, variance: float);
  1737. function CalcVariance(data: PExtended; N: SizeInt; mu: float): float;
  1738. var
  1739. i: SizeInt;
  1740. begin
  1741. if N>=RecursiveSumThreshold then
  1742. result:=CalcVariance(data,SizeUint(N) div 2,mu)+CalcVariance(data+SizeUint(N) div 2,N-SizeUint(N) div 2,mu)
  1743. else
  1744. begin
  1745. result:=0;
  1746. for i:=0 to N-1 do
  1747. result:=result+Sqr(data[i]-mu);
  1748. end;
  1749. end;
  1750. begin
  1751. mu := Mean( data, N );
  1752. variance := CalcVariance( data, N, mu );
  1753. end;
  1754. function stddev(const data : array of Extended) : float; inline;
  1755. begin
  1756. Result:=Stddev(PExtended(@Data[0]),High(Data)+1)
  1757. end;
  1758. function stddev(const data : PExtended; Const N : Integer) : float;
  1759. begin
  1760. StdDev:=Sqrt(Variance(Data,N));
  1761. end;
  1762. procedure meanandstddev(const data : array of Extended;
  1763. var mean,stddev : float); inline;
  1764. begin
  1765. Meanandstddev(PExtended(@Data[0]),High(Data)+1,Mean,stddev);
  1766. end;
  1767. procedure meanandstddev
  1768. ( const data: PExtended;
  1769. const N: Longint;
  1770. var mean,
  1771. stdDev: Float
  1772. );
  1773. var totalVariance: float;
  1774. begin
  1775. MeanAndTotalVariance( data, N, mean, totalVariance );
  1776. if N < 2 then stdDev := 0
  1777. else stdDev := Sqrt( totalVariance / ( N - 1 ) );
  1778. end;
  1779. function variance(const data : array of Extended) : float; inline;
  1780. begin
  1781. Variance:=Variance(PExtended(@Data[0]),High(Data)+1);
  1782. end;
  1783. function variance(const data : PExtended; Const N : Integer) : float;
  1784. begin
  1785. If N=1 then
  1786. Result:=0
  1787. else
  1788. Result:=TotalVariance(Data,N)/(N-1);
  1789. end;
  1790. function totalvariance(const data : array of Extended) : float; inline;
  1791. begin
  1792. Result:=TotalVariance(PExtended(@Data[0]),High(Data)+1);
  1793. end;
  1794. function totalvariance(const data : PExtended;Const N : Integer) : float;
  1795. var mu: float;
  1796. begin
  1797. MeanAndTotalVariance( data, N, mu, result );
  1798. end;
  1799. function popnstddev(const data : array of Extended) : float;
  1800. begin
  1801. PopnStdDev:=Sqrt(PopnVariance(PExtended(@Data[0]),High(Data)+1));
  1802. end;
  1803. function popnstddev(const data : PExtended; Const N : Integer) : float;
  1804. begin
  1805. PopnStdDev:=Sqrt(PopnVariance(Data,N));
  1806. end;
  1807. function popnvariance(const data : array of Extended) : float; inline;
  1808. begin
  1809. popnvariance:=popnvariance(PExtended(@data[0]),high(Data)+1);
  1810. end;
  1811. function popnvariance(const data : PExtended; Const N : Integer) : float;
  1812. begin
  1813. PopnVariance:=TotalVariance(Data,N)/N;
  1814. end;
  1815. procedure momentskewkurtosis(const data : array of Extended;
  1816. out m1,m2,m3,m4,skew,kurtosis : float); inline;
  1817. begin
  1818. momentskewkurtosis(PExtended(@Data[0]),High(Data)+1,m1,m2,m3,m4,skew,kurtosis);
  1819. end;
  1820. procedure momentskewkurtosis(
  1821. const data: pExtended;
  1822. Const N: Integer;
  1823. out m1: float;
  1824. out m2: float;
  1825. out m3: float;
  1826. out m4: float;
  1827. out skew: float;
  1828. out kurtosis: float
  1829. );
  1830. procedure CalcDevSums2to4(data: PExtended; N: SizeInt; m1: float; out m2to4: TMoments2to4);
  1831. var
  1832. tm2, tm3, tm4, dev, dev2: float;
  1833. i: SizeInt;
  1834. m2to4Part0, m2to4Part1: TMoments2to4;
  1835. begin
  1836. if N >= RecursiveSumThreshold then
  1837. begin
  1838. CalcDevSums2to4(data, SizeUint(N) div 2, m1, m2to4Part0);
  1839. CalcDevSums2to4(data + SizeUint(N) div 2, N - SizeUint(N) div 2, m1, m2to4Part1);
  1840. for i := Low(TMoments2to4) to High(TMoments2to4) do
  1841. m2to4[i] := m2to4Part0[i] + m2to4Part1[i];
  1842. end
  1843. else
  1844. begin
  1845. tm2 := 0;
  1846. tm3 := 0;
  1847. tm4 := 0;
  1848. for i := 0 to N - 1 do
  1849. begin
  1850. dev := data[i] - m1;
  1851. dev2 := sqr(dev);
  1852. tm2 := tm2 + dev2;
  1853. tm3 := tm3 + dev2 * dev;
  1854. tm4 := tm4 + sqr(dev2);
  1855. end;
  1856. m2to4[2] := tm2;
  1857. m2to4[3] := tm3;
  1858. m2to4[4] := tm4;
  1859. end;
  1860. end;
  1861. var
  1862. reciprocalN: float;
  1863. m2to4: TMoments2to4;
  1864. begin
  1865. m1 := 0;
  1866. reciprocalN := 1/N;
  1867. m1 := reciprocalN * sum(data, N);
  1868. CalcDevSums2to4(data, N, m1, m2to4);
  1869. m2 := reciprocalN * m2to4[2];
  1870. m3 := reciprocalN * m2to4[3];
  1871. m4 := reciprocalN * m2to4[4];
  1872. skew := m3 / (sqrt(m2)*m2);
  1873. kurtosis := m4 / (m2 * m2);
  1874. end;
  1875. function norm(const data : array of Extended) : float; inline;
  1876. begin
  1877. norm:=Norm(PExtended(@data[0]),High(Data)+1);
  1878. end;
  1879. function norm(const data : PExtended; Const N : Integer) : float;
  1880. begin
  1881. norm:=sqrt(sumofsquares(data,N));
  1882. end;
  1883. {$endif FPC_HAS_TYPE_EXTENDED}
  1884. function MinIntValue(const Data: array of Integer): Integer;
  1885. var
  1886. I: SizeInt;
  1887. begin
  1888. Result := Data[Low(Data)];
  1889. For I := Succ(Low(Data)) To High(Data) Do
  1890. If Data[I] < Result Then Result := Data[I];
  1891. end;
  1892. function MaxIntValue(const Data: array of Integer): Integer;
  1893. var
  1894. I: SizeInt;
  1895. begin
  1896. Result := Data[Low(Data)];
  1897. For I := Succ(Low(Data)) To High(Data) Do
  1898. If Data[I] > Result Then Result := Data[I];
  1899. end;
  1900. function MinValue(const Data: array of Integer): Integer; inline;
  1901. begin
  1902. Result:=MinValue(Pinteger(@Data[0]),High(Data)+1)
  1903. end;
  1904. function MinValue(const Data: PInteger; Const N : Integer): Integer;
  1905. var
  1906. I: SizeInt;
  1907. begin
  1908. Result := Data[0];
  1909. For I := 1 To N-1 do
  1910. If Data[I] < Result Then Result := Data[I];
  1911. end;
  1912. function MaxValue(const Data: array of Integer): Integer; inline;
  1913. begin
  1914. Result:=MaxValue(PInteger(@Data[0]),High(Data)+1)
  1915. end;
  1916. function maxvalue(const data : PInteger; Const N : Integer) : Integer;
  1917. var
  1918. i : SizeInt;
  1919. begin
  1920. { get an initial value }
  1921. maxvalue:=data[0];
  1922. for i:=1 to N-1 do
  1923. if data[i]>maxvalue then
  1924. maxvalue:=data[i];
  1925. end;
  1926. {$ifdef FPC_HAS_TYPE_SINGLE}
  1927. function minvalue(const data : array of Single) : Single; inline;
  1928. begin
  1929. Result:=minvalue(PSingle(@data[0]),High(Data)+1);
  1930. end;
  1931. function minvalue(const data : PSingle; Const N : Integer) : Single;
  1932. var
  1933. i : SizeInt;
  1934. begin
  1935. { get an initial value }
  1936. minvalue:=data[0];
  1937. for i:=1 to N-1 do
  1938. if data[i]<minvalue then
  1939. minvalue:=data[i];
  1940. end;
  1941. function maxvalue(const data : array of Single) : Single; inline;
  1942. begin
  1943. Result:=maxvalue(PSingle(@data[0]),High(Data)+1);
  1944. end;
  1945. function maxvalue(const data : PSingle; Const N : Integer) : Single;
  1946. var
  1947. i : SizeInt;
  1948. begin
  1949. { get an initial value }
  1950. maxvalue:=data[0];
  1951. for i:=1 to N-1 do
  1952. if data[i]>maxvalue then
  1953. maxvalue:=data[i];
  1954. end;
  1955. {$endif FPC_HAS_TYPE_SINGLE}
  1956. {$ifdef FPC_HAS_TYPE_DOUBLE}
  1957. function minvalue(const data : array of Double) : Double; inline;
  1958. begin
  1959. Result:=minvalue(PDouble(@data[0]),High(Data)+1);
  1960. end;
  1961. function minvalue(const data : PDouble; Const N : Integer) : Double;
  1962. var
  1963. i : SizeInt;
  1964. begin
  1965. { get an initial value }
  1966. minvalue:=data[0];
  1967. for i:=1 to N-1 do
  1968. if data[i]<minvalue then
  1969. minvalue:=data[i];
  1970. end;
  1971. function maxvalue(const data : array of Double) : Double; inline;
  1972. begin
  1973. Result:=maxvalue(PDouble(@data[0]),High(Data)+1);
  1974. end;
  1975. function maxvalue(const data : PDouble; Const N : Integer) : Double;
  1976. var
  1977. i : SizeInt;
  1978. begin
  1979. { get an initial value }
  1980. maxvalue:=data[0];
  1981. for i:=1 to N-1 do
  1982. if data[i]>maxvalue then
  1983. maxvalue:=data[i];
  1984. end;
  1985. {$endif FPC_HAS_TYPE_DOUBLE}
  1986. {$ifdef FPC_HAS_TYPE_EXTENDED}
  1987. function minvalue(const data : array of Extended) : Extended; inline;
  1988. begin
  1989. Result:=minvalue(PExtended(@data[0]),High(Data)+1);
  1990. end;
  1991. function minvalue(const data : PExtended; Const N : Integer) : Extended;
  1992. var
  1993. i : SizeInt;
  1994. begin
  1995. { get an initial value }
  1996. minvalue:=data[0];
  1997. for i:=1 to N-1 do
  1998. if data[i]<minvalue then
  1999. minvalue:=data[i];
  2000. end;
  2001. function maxvalue(const data : array of Extended) : Extended; inline;
  2002. begin
  2003. Result:=maxvalue(PExtended(@data[0]),High(Data)+1);
  2004. end;
  2005. function maxvalue(const data : PExtended; Const N : Integer) : Extended;
  2006. var
  2007. i : SizeInt;
  2008. begin
  2009. { get an initial value }
  2010. maxvalue:=data[0];
  2011. for i:=1 to N-1 do
  2012. if data[i]>maxvalue then
  2013. maxvalue:=data[i];
  2014. end;
  2015. {$endif FPC_HAS_TYPE_EXTENDED}
  2016. function Min(a, b: Integer): Integer;inline;
  2017. begin
  2018. if a < b then
  2019. Result := a
  2020. else
  2021. Result := b;
  2022. end;
  2023. function Max(a, b: Integer): Integer;inline;
  2024. begin
  2025. if a > b then
  2026. Result := a
  2027. else
  2028. Result := b;
  2029. end;
  2030. {
  2031. function Min(a, b: Cardinal): Cardinal;inline;
  2032. begin
  2033. if a < b then
  2034. Result := a
  2035. else
  2036. Result := b;
  2037. end;
  2038. function Max(a, b: Cardinal): Cardinal;inline;
  2039. begin
  2040. if a > b then
  2041. Result := a
  2042. else
  2043. Result := b;
  2044. end;
  2045. }
  2046. function Min(a, b: Int64): Int64;inline;
  2047. begin
  2048. if a < b then
  2049. Result := a
  2050. else
  2051. Result := b;
  2052. end;
  2053. function Max(a, b: Int64): Int64;inline;
  2054. begin
  2055. if a > b then
  2056. Result := a
  2057. else
  2058. Result := b;
  2059. end;
  2060. function Min(a, b: QWord): QWord; inline;
  2061. begin
  2062. if a < b then
  2063. Result := a
  2064. else
  2065. Result := b;
  2066. end;
  2067. function Max(a, b: QWord): Qword;inline;
  2068. begin
  2069. if a > b then
  2070. Result := a
  2071. else
  2072. Result := b;
  2073. end;
  2074. {$ifdef FPC_HAS_TYPE_SINGLE}
  2075. function Min(a, b: Single): Single;inline;
  2076. begin
  2077. if a < b then
  2078. Result := a
  2079. else
  2080. Result := b;
  2081. end;
  2082. function Max(a, b: Single): Single;inline;
  2083. begin
  2084. if a > b then
  2085. Result := a
  2086. else
  2087. Result := b;
  2088. end;
  2089. {$endif FPC_HAS_TYPE_SINGLE}
  2090. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2091. function Min(a, b: Double): Double;inline;
  2092. begin
  2093. if a < b then
  2094. Result := a
  2095. else
  2096. Result := b;
  2097. end;
  2098. function Max(a, b: Double): Double;inline;
  2099. begin
  2100. if a > b then
  2101. Result := a
  2102. else
  2103. Result := b;
  2104. end;
  2105. {$endif FPC_HAS_TYPE_DOUBLE}
  2106. {$ifdef FPC_HAS_TYPE_EXTENDED}
  2107. function Min(a, b: Extended): Extended;inline;
  2108. begin
  2109. if a < b then
  2110. Result := a
  2111. else
  2112. Result := b;
  2113. end;
  2114. function Max(a, b: Extended): Extended;inline;
  2115. begin
  2116. if a > b then
  2117. Result := a
  2118. else
  2119. Result := b;
  2120. end;
  2121. {$endif FPC_HAS_TYPE_EXTENDED}
  2122. function InRange(const AValue, AMin, AMax: Integer): Boolean;inline;
  2123. begin
  2124. Result:=(AValue>=AMin) and (AValue<=AMax);
  2125. end;
  2126. function InRange(const AValue, AMin, AMax: Int64): Boolean;inline;
  2127. begin
  2128. Result:=(AValue>=AMin) and (AValue<=AMax);
  2129. end;
  2130. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2131. function InRange(const AValue, AMin, AMax: Double): Boolean;inline;
  2132. begin
  2133. Result:=(AValue>=AMin) and (AValue<=AMax);
  2134. end;
  2135. {$endif FPC_HAS_TYPE_DOUBLE}
  2136. function EnsureRange(const AValue, AMin, AMax: Integer): Integer;inline;
  2137. begin
  2138. Result:=AValue;
  2139. If Result<AMin then
  2140. Result:=AMin;
  2141. if Result>AMax then
  2142. Result:=AMax;
  2143. end;
  2144. function EnsureRange(const AValue, AMin, AMax: Int64): Int64;inline;
  2145. begin
  2146. Result:=AValue;
  2147. If Result<AMin then
  2148. Result:=AMin;
  2149. if Result>AMax then
  2150. Result:=AMax;
  2151. end;
  2152. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2153. function EnsureRange(const AValue, AMin, AMax: Double): Double;inline;
  2154. begin
  2155. Result:=AValue;
  2156. If Result<AMin then
  2157. Result:=AMin;
  2158. if Result>AMax then
  2159. Result:=AMax;
  2160. end;
  2161. {$endif FPC_HAS_TYPE_DOUBLE}
  2162. Const
  2163. EZeroResolution = Extended(1E-16);
  2164. DZeroResolution = Double(1E-12);
  2165. SZeroResolution = Single(1E-4);
  2166. function IsZero(const A: Single; Epsilon: Single): Boolean;
  2167. begin
  2168. if (Epsilon=0) then
  2169. Epsilon:=SZeroResolution;
  2170. Result:=Abs(A)<=Epsilon;
  2171. end;
  2172. function IsZero(const A: Single): Boolean;inline;
  2173. begin
  2174. Result:=IsZero(A,single(SZeroResolution));
  2175. end;
  2176. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2177. function IsZero(const A: Double; Epsilon: Double): Boolean;
  2178. begin
  2179. if (Epsilon=0) then
  2180. Epsilon:=DZeroResolution;
  2181. Result:=Abs(A)<=Epsilon;
  2182. end;
  2183. function IsZero(const A: Double): Boolean;inline;
  2184. begin
  2185. Result:=IsZero(A,DZeroResolution);
  2186. end;
  2187. {$endif FPC_HAS_TYPE_DOUBLE}
  2188. {$ifdef FPC_HAS_TYPE_EXTENDED}
  2189. function IsZero(const A: Extended; Epsilon: Extended): Boolean;
  2190. begin
  2191. if (Epsilon=0) then
  2192. Epsilon:=EZeroResolution;
  2193. Result:=Abs(A)<=Epsilon;
  2194. end;
  2195. function IsZero(const A: Extended): Boolean;inline;
  2196. begin
  2197. Result:=IsZero(A,EZeroResolution);
  2198. end;
  2199. {$endif FPC_HAS_TYPE_EXTENDED}
  2200. type
  2201. TSplitDouble = packed record
  2202. cards: Array[0..1] of cardinal;
  2203. end;
  2204. TSplitExtended = packed record
  2205. cards: Array[0..1] of cardinal;
  2206. w: word;
  2207. end;
  2208. function IsNan(const d : Single): Boolean; overload;
  2209. begin
  2210. result:=(longword(d) and $7fffffff)>$7f800000;
  2211. end;
  2212. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2213. function IsNan(const d : Double): Boolean;
  2214. var
  2215. fraczero, expMaximal: boolean;
  2216. begin
  2217. {$if defined(FPC_BIG_ENDIAN) or defined(FPC_DOUBLE_HILO_SWAPPED)}
  2218. expMaximal := ((TSplitDouble(d).cards[0] shr 20) and $7ff) = 2047;
  2219. fraczero:= (TSplitDouble(d).cards[0] and $fffff = 0) and
  2220. (TSplitDouble(d).cards[1] = 0);
  2221. {$else FPC_BIG_ENDIAN}
  2222. expMaximal := ((TSplitDouble(d).cards[1] shr 20) and $7ff) = 2047;
  2223. fraczero := (TSplitDouble(d).cards[1] and $fffff = 0) and
  2224. (TSplitDouble(d).cards[0] = 0);
  2225. {$endif FPC_BIG_ENDIAN}
  2226. Result:=expMaximal and not(fraczero);
  2227. end;
  2228. {$endif FPC_HAS_TYPE_DOUBLE}
  2229. {$ifdef FPC_HAS_TYPE_EXTENDED}
  2230. function IsNan(const d : Extended): Boolean; overload;
  2231. var
  2232. fraczero, expMaximal: boolean;
  2233. begin
  2234. {$ifdef FPC_BIG_ENDIAN}
  2235. {$error no support for big endian extended type yet}
  2236. {$else FPC_BIG_ENDIAN}
  2237. expMaximal := (TSplitExtended(d).w and $7fff) = 32767;
  2238. fraczero := (TSplitExtended(d).cards[0] = 0) and
  2239. ((TSplitExtended(d).cards[1] and $7fffffff) = 0);
  2240. {$endif FPC_BIG_ENDIAN}
  2241. Result:=expMaximal and not(fraczero);
  2242. end;
  2243. {$endif FPC_HAS_TYPE_EXTENDED}
  2244. function IsInfinite(const d : Single): Boolean; overload;
  2245. begin
  2246. result:=(longword(d) and $7fffffff)=$7f800000;
  2247. end;
  2248. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2249. function IsInfinite(const d : Double): Boolean; overload;
  2250. var
  2251. fraczero, expMaximal: boolean;
  2252. begin
  2253. {$if defined(FPC_BIG_ENDIAN) or defined(FPC_DOUBLE_HILO_SWAPPED)}
  2254. expMaximal := ((TSplitDouble(d).cards[0] shr 20) and $7ff) = 2047;
  2255. fraczero:= (TSplitDouble(d).cards[0] and $fffff = 0) and
  2256. (TSplitDouble(d).cards[1] = 0);
  2257. {$else FPC_BIG_ENDIAN}
  2258. expMaximal := ((TSplitDouble(d).cards[1] shr 20) and $7ff) = 2047;
  2259. fraczero := (TSplitDouble(d).cards[1] and $fffff = 0) and
  2260. (TSplitDouble(d).cards[0] = 0);
  2261. {$endif FPC_BIG_ENDIAN}
  2262. Result:=expMaximal and fraczero;
  2263. end;
  2264. {$endif FPC_HAS_TYPE_DOUBLE}
  2265. {$ifdef FPC_HAS_TYPE_EXTENDED}
  2266. function IsInfinite(const d : Extended): Boolean; overload;
  2267. var
  2268. fraczero, expMaximal: boolean;
  2269. begin
  2270. {$ifdef FPC_BIG_ENDIAN}
  2271. {$error no support for big endian extended type yet}
  2272. {$else FPC_BIG_ENDIAN}
  2273. expMaximal := (TSplitExtended(d).w and $7fff) = 32767;
  2274. fraczero := (TSplitExtended(d).cards[0] = 0) and
  2275. ((TSplitExtended(d).cards[1] and $7fffffff) = 0);
  2276. {$endif FPC_BIG_ENDIAN}
  2277. Result:=expMaximal and fraczero;
  2278. end;
  2279. {$endif FPC_HAS_TYPE_EXTENDED}
  2280. function copysign(x,y: float): float;
  2281. begin
  2282. {$if defined(FPC_HAS_TYPE_FLOAT128)}
  2283. {$error copysign not yet implemented for float128}
  2284. {$elseif defined(FPC_HAS_TYPE_EXTENDED)}
  2285. TSplitExtended(x).w:=(TSplitExtended(x).w and $7fff) or (TSplitExtended(y).w and $8000);
  2286. {$elseif defined(FPC_HAS_TYPE_DOUBLE)}
  2287. {$if defined(FPC_BIG_ENDIAN) or defined(FPC_DOUBLE_HILO_SWAPPED)}
  2288. TSplitDouble(x).cards[0]:=(TSplitDouble(x).cards[0] and $7fffffff) or (TSplitDouble(y).cards[0] and longword($80000000));
  2289. {$else}
  2290. TSplitDouble(x).cards[1]:=(TSplitDouble(x).cards[1] and $7fffffff) or (TSplitDouble(y).cards[1] and longword($80000000));
  2291. {$endif}
  2292. {$else}
  2293. longword(x):=longword(x and $7fffffff) or (longword(y) and longword($80000000));
  2294. {$endif}
  2295. result:=x;
  2296. end;
  2297. {$ifdef FPC_HAS_TYPE_EXTENDED}
  2298. function SameValue(const A, B: Extended; Epsilon: Extended): Boolean;
  2299. begin
  2300. if (Epsilon=0) then
  2301. Epsilon:=Max(Min(Abs(A),Abs(B))*EZeroResolution,EZeroResolution);
  2302. if (A>B) then
  2303. Result:=((A-B)<=Epsilon)
  2304. else
  2305. Result:=((B-A)<=Epsilon);
  2306. end;
  2307. function SameValue(const A, B: Extended): Boolean;inline;
  2308. begin
  2309. Result:=SameValue(A,B,0.0);
  2310. end;
  2311. {$endif FPC_HAS_TYPE_EXTENDED}
  2312. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2313. function SameValue(const A, B: Double): Boolean;inline;
  2314. begin
  2315. Result:=SameValue(A,B,0.0);
  2316. end;
  2317. function SameValue(const A, B: Double; Epsilon: Double): Boolean;
  2318. begin
  2319. if (Epsilon=0) then
  2320. Epsilon:=Max(Min(Abs(A),Abs(B))*DZeroResolution,DZeroResolution);
  2321. if (A>B) then
  2322. Result:=((A-B)<=Epsilon)
  2323. else
  2324. Result:=((B-A)<=Epsilon);
  2325. end;
  2326. {$endif FPC_HAS_TYPE_DOUBLE}
  2327. function SameValue(const A, B: Single): Boolean;inline;
  2328. begin
  2329. Result:=SameValue(A,B,0);
  2330. end;
  2331. function SameValue(const A, B: Single; Epsilon: Single): Boolean;
  2332. begin
  2333. if (Epsilon=0) then
  2334. Epsilon:=Max(Min(Abs(A),Abs(B))*SZeroResolution,SZeroResolution);
  2335. if (A>B) then
  2336. Result:=((A-B)<=Epsilon)
  2337. else
  2338. Result:=((B-A)<=Epsilon);
  2339. end;
  2340. // Some CPUs probably allow a faster way of doing this in a single operation...
  2341. // There weshould define FPC_MATH_HAS_CPUDIVMOD in the header mathuh.inc and implement it using asm.
  2342. {$ifndef FPC_MATH_HAS_DIVMOD}
  2343. procedure DivMod(Dividend: LongInt; Divisor: Word; var Result, Remainder: Word);
  2344. begin
  2345. if Dividend < 0 then
  2346. begin
  2347. { Use DivMod with >=0 dividend }
  2348. Dividend:=-Dividend;
  2349. { The documented behavior of Pascal's div/mod operators and DivMod
  2350. on negative dividends is to return Result closer to zero and
  2351. a negative Remainder. Which means that we can just negate both
  2352. Result and Remainder, and all it's Ok. }
  2353. Result:=-(Dividend Div Divisor);
  2354. Remainder:=-(Dividend+(Result*Divisor));
  2355. end
  2356. else
  2357. begin
  2358. Result:=Dividend Div Divisor;
  2359. Remainder:=Dividend-(Result*Divisor);
  2360. end;
  2361. end;
  2362. procedure DivMod(Dividend: LongInt; Divisor: Word; var Result, Remainder: SmallInt);
  2363. begin
  2364. if Dividend < 0 then
  2365. begin
  2366. { Use DivMod with >=0 dividend }
  2367. Dividend:=-Dividend;
  2368. { The documented behavior of Pascal's div/mod operators and DivMod
  2369. on negative dividends is to return Result closer to zero and
  2370. a negative Remainder. Which means that we can just negate both
  2371. Result and Remainder, and all it's Ok. }
  2372. Result:=-(Dividend Div Divisor);
  2373. Remainder:=-(Dividend+(Result*Divisor));
  2374. end
  2375. else
  2376. begin
  2377. Result:=Dividend Div Divisor;
  2378. Remainder:=Dividend-(Result*Divisor);
  2379. end;
  2380. end;
  2381. procedure DivMod(Dividend: DWord; Divisor: DWord; var Result, Remainder: DWord);
  2382. begin
  2383. Result:=Dividend Div Divisor;
  2384. Remainder:=Dividend-(Result*Divisor);
  2385. end;
  2386. procedure DivMod(Dividend: LongInt; Divisor: LongInt; var Result, Remainder: LongInt);
  2387. begin
  2388. if Dividend < 0 then
  2389. begin
  2390. { Use DivMod with >=0 dividend }
  2391. Dividend:=-Dividend;
  2392. { The documented behavior of Pascal's div/mod operators and DivMod
  2393. on negative dividends is to return Result closer to zero and
  2394. a negative Remainder. Which means that we can just negate both
  2395. Result and Remainder, and all it's Ok. }
  2396. Result:=-(Dividend Div Divisor);
  2397. Remainder:=-(Dividend+(Result*Divisor));
  2398. end
  2399. else
  2400. begin
  2401. Result:=Dividend Div Divisor;
  2402. Remainder:=Dividend-(Result*Divisor);
  2403. end;
  2404. end;
  2405. {$endif FPC_MATH_HAS_DIVMOD}
  2406. { Floating point modulo}
  2407. {$ifdef FPC_HAS_TYPE_SINGLE}
  2408. function FMod(const a, b: Single): Single;inline;overload;
  2409. begin
  2410. result:= a-b * Int(a/b);
  2411. end;
  2412. {$endif FPC_HAS_TYPE_SINGLE}
  2413. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2414. function FMod(const a, b: Double): Double;inline;overload;
  2415. begin
  2416. result:= a-b * Int(a/b);
  2417. end;
  2418. {$endif FPC_HAS_TYPE_DOUBLE}
  2419. {$ifdef FPC_HAS_TYPE_EXTENDED}
  2420. function FMod(const a, b: Extended): Extended;inline;overload;
  2421. begin
  2422. result:= a-b * Int(a/b);
  2423. end;
  2424. {$endif FPC_HAS_TYPE_EXTENDED}
  2425. operator mod(const a,b:float) c:float;inline;
  2426. begin
  2427. c:= a-b * Int(a/b);
  2428. if SameValue(abs(c),abs(b)) then
  2429. c:=0.0;
  2430. end;
  2431. function ifthen(val:boolean;const iftrue:integer; const iffalse:integer= 0) :integer;
  2432. begin
  2433. if val then result:=iftrue else result:=iffalse;
  2434. end;
  2435. function ifthen(val:boolean;const iftrue:int64 ; const iffalse:int64 = 0) :int64;
  2436. begin
  2437. if val then result:=iftrue else result:=iffalse;
  2438. end;
  2439. function ifthen(val:boolean;const iftrue:double ; const iffalse:double =0.0):double;
  2440. begin
  2441. if val then result:=iftrue else result:=iffalse;
  2442. end;
  2443. // dilemma here. asm can do the two comparisons in one go?
  2444. // but pascal is portable and can be inlined. Ah well, we need purepascal's anyway:
  2445. function CompareValue(const A, B : Integer): TValueRelationship;
  2446. begin
  2447. result:=GreaterThanValue;
  2448. if a=b then
  2449. result:=EqualsValue
  2450. else
  2451. if a<b then
  2452. result:=LessThanValue;
  2453. end;
  2454. function CompareValue(const A, B: Int64): TValueRelationship;
  2455. begin
  2456. result:=GreaterThanValue;
  2457. if a=b then
  2458. result:=EqualsValue
  2459. else
  2460. if a<b then
  2461. result:=LessThanValue;
  2462. end;
  2463. function CompareValue(const A, B: QWord): TValueRelationship;
  2464. begin
  2465. result:=GreaterThanValue;
  2466. if a=b then
  2467. result:=EqualsValue
  2468. else
  2469. if a<b then
  2470. result:=LessThanValue;
  2471. end;
  2472. {$ifdef FPC_HAS_TYPE_SINGLE}
  2473. function CompareValue(const A, B: Single; delta: Single = 0.0): TValueRelationship;
  2474. begin
  2475. result:=GreaterThanValue;
  2476. if abs(a-b)<=delta then
  2477. result:=EqualsValue
  2478. else
  2479. if a<b then
  2480. result:=LessThanValue;
  2481. end;
  2482. {$endif}
  2483. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2484. function CompareValue(const A, B: Double; delta: Double = 0.0): TValueRelationship;
  2485. begin
  2486. result:=GreaterThanValue;
  2487. if abs(a-b)<=delta then
  2488. result:=EqualsValue
  2489. else
  2490. if a<b then
  2491. result:=LessThanValue;
  2492. end;
  2493. {$endif}
  2494. {$ifdef FPC_HAS_TYPE_EXTENDED}
  2495. function CompareValue (const A, B: Extended; delta: Extended = 0.0): TValueRelationship;
  2496. begin
  2497. result:=GreaterThanValue;
  2498. if abs(a-b)<=delta then
  2499. result:=EqualsValue
  2500. else
  2501. if a<b then
  2502. result:=LessThanValue;
  2503. end;
  2504. {$endif}
  2505. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2506. function RoundTo(const AValue: Double; const Digits: TRoundToRange): Double;
  2507. var
  2508. RV : Double;
  2509. begin
  2510. RV:=IntPower(10,Digits);
  2511. Result:=Round(AValue/RV)*RV;
  2512. end;
  2513. {$endif}
  2514. {$ifdef FPC_HAS_TYPE_EXTENDED}
  2515. function RoundTo(const AVAlue: Extended; const Digits: TRoundToRange): Extended;
  2516. var
  2517. RV : Extended;
  2518. begin
  2519. RV:=IntPower(10,Digits);
  2520. Result:=Round(AValue/RV)*RV;
  2521. end;
  2522. {$endif}
  2523. {$ifdef FPC_HAS_TYPE_SINGLE}
  2524. function RoundTo(const AValue: Single; const Digits: TRoundToRange): Single;
  2525. var
  2526. RV : Single;
  2527. begin
  2528. RV:=IntPower(10,Digits);
  2529. Result:=Round(AValue/RV)*RV;
  2530. end;
  2531. {$endif}
  2532. {$ifdef FPC_HAS_TYPE_SINGLE}
  2533. function SimpleRoundTo(const AValue: Single; const Digits: TRoundToRange = -2): Single;
  2534. var
  2535. RV : Single;
  2536. begin
  2537. RV := IntPower(10, -Digits);
  2538. if AValue < 0 then
  2539. Result := Int((AValue*RV) - 0.5)/RV
  2540. else
  2541. Result := Int((AValue*RV) + 0.5)/RV;
  2542. end;
  2543. {$endif}
  2544. {$ifdef FPC_HAS_TYPE_DOUBLE}
  2545. function SimpleRoundTo(const AValue: Double; const Digits: TRoundToRange = -2): Double;
  2546. var
  2547. RV : Double;
  2548. begin
  2549. RV := IntPower(10, -Digits);
  2550. if AValue < 0 then
  2551. Result := Int((AValue*RV) - 0.5)/RV
  2552. else
  2553. Result := Int((AValue*RV) + 0.5)/RV;
  2554. end;
  2555. {$endif}
  2556. {$ifdef FPC_HAS_TYPE_EXTENDED}
  2557. function SimpleRoundTo(const AValue: Extended; const Digits: TRoundToRange = -2): Extended;
  2558. var
  2559. RV : Extended;
  2560. begin
  2561. RV := IntPower(10, -Digits);
  2562. if AValue < 0 then
  2563. Result := Int((AValue*RV) - 0.5)/RV
  2564. else
  2565. Result := Int((AValue*RV) + 0.5)/RV;
  2566. end;
  2567. {$endif}
  2568. function RandomFrom(const AValues: array of Double): Double; overload;
  2569. begin
  2570. result:=AValues[random(High(AValues)+1)];
  2571. end;
  2572. function RandomFrom(const AValues: array of Integer): Integer; overload;
  2573. begin
  2574. result:=AValues[random(High(AValues)+1)];
  2575. end;
  2576. function RandomFrom(const AValues: array of Int64): Int64; overload;
  2577. begin
  2578. result:=AValues[random(High(AValues)+1)];
  2579. end;
  2580. {$if FPC_FULLVERSION >=30101}
  2581. generic function RandomFrom<T>(const AValues:array of T):T;
  2582. begin
  2583. result:=AValues[random(High(AValues)+1)];
  2584. end;
  2585. {$endif}
  2586. function FutureValue(ARate: Float; NPeriods: Integer;
  2587. APayment, APresentValue: Float; APaymentTime: TPaymentTime): Float;
  2588. var
  2589. q, qn, factor: Float;
  2590. begin
  2591. if ARate = 0 then
  2592. Result := -APresentValue - APayment * NPeriods
  2593. else begin
  2594. q := 1.0 + ARate;
  2595. qn := power(q, NPeriods);
  2596. factor := (qn - 1) / (q - 1);
  2597. if APaymentTime = ptStartOfPeriod then
  2598. factor := factor * q;
  2599. Result := -(APresentValue * qn + APayment*factor);
  2600. end;
  2601. end;
  2602. function InterestRate(NPeriods: Integer; APayment, APresentValue, AFutureValue: Float;
  2603. APaymentTime: TPaymentTime): Float;
  2604. { The interest rate cannot be calculated analytically. We solve the equation
  2605. numerically by means of the Newton method:
  2606. - guess value for the interest reate
  2607. - calculate at which interest rate the tangent of the curve fv(rate)
  2608. (straight line!) has the requested future vale.
  2609. - use this rate for the next iteration. }
  2610. const
  2611. DELTA = 0.001;
  2612. EPS = 1E-9; // required precision of interest rate (after typ. 6 iterations)
  2613. MAXIT = 20; // max iteration count to protect agains non-convergence
  2614. var
  2615. r1, r2, dr: Float;
  2616. fv1, fv2: Float;
  2617. iteration: Integer;
  2618. begin
  2619. iteration := 0;
  2620. r1 := 0.05; // inital guess
  2621. repeat
  2622. r2 := r1 + DELTA;
  2623. fv1 := FutureValue(r1, NPeriods, APayment, APresentValue, APaymentTime);
  2624. fv2 := FutureValue(r2, NPeriods, APayment, APresentValue, APaymentTime);
  2625. dr := (AFutureValue - fv1) / (fv2 - fv1) * delta; // tangent at fv(r)
  2626. r1 := r1 + dr; // next guess
  2627. inc(iteration);
  2628. until (abs(dr) < EPS) or (iteration >= MAXIT);
  2629. Result := r1;
  2630. end;
  2631. function NumberOfPeriods(ARate, APayment, APresentValue, AFutureValue: Float;
  2632. APaymentTime: TPaymentTime): Float;
  2633. { Solve the cash flow equation (1) for q^n and take the logarithm }
  2634. var
  2635. q, x1, x2: Float;
  2636. begin
  2637. if ARate = 0 then
  2638. Result := -(APresentValue + AFutureValue) / APayment
  2639. else begin
  2640. q := 1.0 + ARate;
  2641. if APaymentTime = ptStartOfPeriod then
  2642. APayment := APayment * q;
  2643. x1 := APayment - AFutureValue * ARate;
  2644. x2 := APayment + APresentValue * ARate;
  2645. if (x2 = 0) // we have to divide by x2
  2646. or (sign(x1) * sign(x2) < 0) // the argument of the log is negative
  2647. then
  2648. Result := Infinity
  2649. else begin
  2650. Result := ln(x1/x2) / ln(q);
  2651. end;
  2652. end;
  2653. end;
  2654. function Payment(ARate: Float; NPeriods: Integer;
  2655. APresentValue, AFutureValue: Float; APaymentTime: TPaymentTime): Float;
  2656. var
  2657. q, qn, factor: Float;
  2658. begin
  2659. if ARate = 0 then
  2660. Result := -(AFutureValue + APresentValue) / NPeriods
  2661. else begin
  2662. q := 1.0 + ARate;
  2663. qn := power(q, NPeriods);
  2664. factor := (qn - 1) / (q - 1);
  2665. if APaymentTime = ptStartOfPeriod then
  2666. factor := factor * q;
  2667. Result := -(AFutureValue + APresentValue * qn) / factor;
  2668. end;
  2669. end;
  2670. function PresentValue(ARate: Float; NPeriods: Integer;
  2671. APayment, AFutureValue: Float; APaymentTime: TPaymentTime): Float;
  2672. var
  2673. q, qn, factor: Float;
  2674. begin
  2675. if ARate = 0.0 then
  2676. Result := -AFutureValue - APayment * NPeriods
  2677. else begin
  2678. q := 1.0 + ARate;
  2679. qn := power(q, NPeriods);
  2680. factor := (qn - 1) / (q - 1);
  2681. if APaymentTime = ptStartOfPeriod then
  2682. factor := factor * q;
  2683. Result := -(AFutureValue + APayment*factor) / qn;
  2684. end;
  2685. end;
  2686. {$else}
  2687. implementation
  2688. {$endif FPUNONE}
  2689. end.