math.pp 82 KB

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