math.pp 83 KB

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