math.nim 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## *Constructive mathematics is naturally typed.* -- Simon Thompson
  10. ##
  11. ## Basic math routines for Nim.
  12. ##
  13. ## Note that the trigonometric functions naturally operate on radians.
  14. ## The helper functions `degToRad <#degToRad,T>`_ and `radToDeg <#radToDeg,T>`_
  15. ## provide conversion between radians and degrees.
  16. runnableExamples:
  17. from std/fenv import epsilon
  18. from std/random import rand
  19. proc generateGaussianNoise(mu: float = 0.0, sigma: float = 1.0): (float, float) =
  20. # Generates values from a normal distribution.
  21. # Translated from https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform#Implementation.
  22. var u1: float
  23. var u2: float
  24. while true:
  25. u1 = rand(1.0)
  26. u2 = rand(1.0)
  27. if u1 > epsilon(float): break
  28. let mag = sigma * sqrt(-2 * ln(u1))
  29. let z0 = mag * cos(2 * PI * u2) + mu
  30. let z1 = mag * sin(2 * PI * u2) + mu
  31. (z0, z1)
  32. echo generateGaussianNoise()
  33. ## This module is available for the `JavaScript target
  34. ## <backends.html#backends-the-javascript-target>`_.
  35. ##
  36. ## See also
  37. ## ========
  38. ## * `complex module <complex.html>`_ for complex numbers and their
  39. ## mathematical operations
  40. ## * `rationals module <rationals.html>`_ for rational numbers and their
  41. ## mathematical operations
  42. ## * `fenv module <fenv.html>`_ for handling of floating-point rounding
  43. ## and exceptions (overflow, zero-divide, etc.)
  44. ## * `random module <random.html>`_ for a fast and tiny random number generator
  45. ## * `stats module <stats.html>`_ for statistical analysis
  46. ## * `strformat module <strformat.html>`_ for formatting floats for printing
  47. ## * `system module <system.html>`_ for some very basic and trivial math operators
  48. ## (`shr`, `shl`, `xor`, `clamp`, etc.)
  49. import std/private/since
  50. {.push debugger: off.} # the user does not want to trace a part
  51. # of the standard library!
  52. import bitops, fenv
  53. when defined(nimPreviewSlimSystem):
  54. import std/assertions
  55. when defined(c) or defined(cpp):
  56. proc c_isnan(x: float): bool {.importc: "isnan", header: "<math.h>".}
  57. # a generic like `x: SomeFloat` might work too if this is implemented via a C macro.
  58. proc c_copysign(x, y: cfloat): cfloat {.importc: "copysignf", header: "<math.h>".}
  59. proc c_copysign(x, y: cdouble): cdouble {.importc: "copysign", header: "<math.h>".}
  60. proc c_signbit(x: SomeFloat): cint {.importc: "signbit", header: "<math.h>".}
  61. # don't export `c_frexp` in the future and remove `c_frexp2`.
  62. func c_frexp2(x: cfloat, exponent: var cint): cfloat {.
  63. importc: "frexpf", header: "<math.h>".}
  64. func c_frexp2(x: cdouble, exponent: var cint): cdouble {.
  65. importc: "frexp", header: "<math.h>".}
  66. type
  67. div_t {.importc, header: "<stdlib.h>".} = object
  68. quot: cint
  69. rem: cint
  70. ldiv_t {.importc, header: "<stdlib.h>".} = object
  71. quot: clong
  72. rem: clong
  73. lldiv_t {.importc, header: "<stdlib.h>".} = object
  74. quot: clonglong
  75. rem: clonglong
  76. when cint isnot clong:
  77. func divmod_c(x, y: cint): div_t {.importc: "div", header: "<stdlib.h>".}
  78. when clong isnot clonglong:
  79. func divmod_c(x, y: clonglong): lldiv_t {.importc: "lldiv", header: "<stdlib.h>".}
  80. func divmod_c(x, y: clong): ldiv_t {.importc: "ldiv", header: "<stdlib.h>".}
  81. func divmod*[T: SomeInteger](x, y: T): (T, T) {.inline.} =
  82. ## Specialized instructions for computing both division and modulus.
  83. ## Return structure is: (quotient, remainder)
  84. runnableExamples:
  85. doAssert divmod(5, 2) == (2, 1)
  86. doAssert divmod(5, -3) == (-1, 2)
  87. when T is cint | clong | clonglong:
  88. when compileOption("overflowChecks"):
  89. if y == 0:
  90. raise new(DivByZeroDefect)
  91. elif (x == T.low and y == -1.T):
  92. raise new(OverflowDefect)
  93. let res = divmod_c(x, y)
  94. result[0] = res.quot
  95. result[1] = res.rem
  96. else:
  97. result[0] = x div y
  98. result[1] = x mod y
  99. func binom*(n, k: int): int =
  100. ## Computes the [binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient).
  101. runnableExamples:
  102. doAssert binom(6, 2) == 15
  103. doAssert binom(-6, 2) == 1
  104. doAssert binom(6, 0) == 1
  105. if k <= 0: return 1
  106. if 2 * k > n: return binom(n, n - k)
  107. result = n
  108. for i in countup(2, k):
  109. result = (result * (n + 1 - i)) div i
  110. func createFactTable[N: static[int]]: array[N, int] =
  111. result[0] = 1
  112. for i in 1 ..< N:
  113. result[i] = result[i - 1] * i
  114. func fac*(n: int): int =
  115. ## Computes the [factorial](https://en.wikipedia.org/wiki/Factorial) of
  116. ## a non-negative integer `n`.
  117. ##
  118. ## **See also:**
  119. ## * `prod func <#prod,openArray[T]>`_
  120. runnableExamples:
  121. doAssert fac(0) == 1
  122. doAssert fac(4) == 24
  123. doAssert fac(10) == 3628800
  124. const factTable =
  125. when sizeof(int) == 2:
  126. createFactTable[5]()
  127. elif sizeof(int) == 4:
  128. createFactTable[13]()
  129. else:
  130. createFactTable[21]()
  131. assert(n >= 0, $n & " must not be negative.")
  132. assert(n < factTable.len, $n & " is too large to look up in the table")
  133. factTable[n]
  134. {.push checks: off, line_dir: off, stack_trace: off.}
  135. when defined(posix) and not defined(genode):
  136. {.passl: "-lm".}
  137. const
  138. PI* = 3.1415926535897932384626433 ## The circle constant PI (Ludolph's number).
  139. TAU* = 2.0 * PI ## The circle constant TAU (= 2 * PI).
  140. E* = 2.71828182845904523536028747 ## Euler's number.
  141. MaxFloat64Precision* = 16 ## Maximum number of meaningful digits
  142. ## after the decimal point for Nim's
  143. ## `float64` type.
  144. MaxFloat32Precision* = 8 ## Maximum number of meaningful digits
  145. ## after the decimal point for Nim's
  146. ## `float32` type.
  147. MaxFloatPrecision* = MaxFloat64Precision ## Maximum number of
  148. ## meaningful digits
  149. ## after the decimal point
  150. ## for Nim's `float` type.
  151. MinFloatNormal* = 2.225073858507201e-308 ## Smallest normal number for Nim's
  152. ## `float` type (= 2^-1022).
  153. RadPerDeg = PI / 180.0 ## Number of radians per degree.
  154. type
  155. FloatClass* = enum ## Describes the class a floating point value belongs to.
  156. ## This is the type that is returned by the
  157. ## `classify func <#classify,float>`_.
  158. fcNormal, ## value is an ordinary nonzero floating point value
  159. fcSubnormal, ## value is a subnormal (a very small) floating point value
  160. fcZero, ## value is zero
  161. fcNegZero, ## value is the negative zero
  162. fcNan, ## value is Not a Number (NaN)
  163. fcInf, ## value is positive infinity
  164. fcNegInf ## value is negative infinity
  165. func isNaN*(x: SomeFloat): bool {.inline, since: (1,5,1).} =
  166. ## Returns whether `x` is a `NaN`, more efficiently than via `classify(x) == fcNan`.
  167. ## Works even with `--passc:-ffast-math`.
  168. runnableExamples:
  169. doAssert NaN.isNaN
  170. doAssert not Inf.isNaN
  171. doAssert not isNaN(3.1415926)
  172. template fn: untyped = result = x != x
  173. when nimvm: fn()
  174. else:
  175. when defined(js): fn()
  176. else: result = c_isnan(x)
  177. when defined(js):
  178. import std/private/jsutils
  179. proc toBitsImpl(x: float): array[2, uint32] =
  180. let buffer = newArrayBuffer(8)
  181. let a = newFloat64Array(buffer)
  182. let b = newUint32Array(buffer)
  183. a[0] = x
  184. {.emit: "`result` = `b`;".}
  185. # result = cast[array[2, uint32]](b)
  186. proc jsSetSign(x: float, sgn: bool): float =
  187. let buffer = newArrayBuffer(8)
  188. let a = newFloat64Array(buffer)
  189. let b = newUint32Array(buffer)
  190. a[0] = x
  191. asm """
  192. function updateBit(num, bitPos, bitVal) {
  193. return (num & ~(1 << bitPos)) | (bitVal << bitPos);
  194. }
  195. `b`[1] = updateBit(`b`[1], 31, `sgn`);
  196. `result` = `a`[0]
  197. """
  198. proc signbit*(x: SomeFloat): bool {.inline, since: (1, 5, 1).} =
  199. ## Returns true if `x` is negative, false otherwise.
  200. runnableExamples:
  201. doAssert not signbit(0.0)
  202. doAssert signbit(-0.0)
  203. doAssert signbit(-0.1)
  204. doAssert not signbit(0.1)
  205. when defined(js):
  206. let uintBuffer = toBitsImpl(x)
  207. result = (uintBuffer[1] shr 31) != 0
  208. else:
  209. result = c_signbit(x) != 0
  210. func copySign*[T: SomeFloat](x, y: T): T {.inline, since: (1, 5, 1).} =
  211. ## Returns a value with the magnitude of `x` and the sign of `y`;
  212. ## this works even if x or y are NaN, infinity or zero, all of which can carry a sign.
  213. runnableExamples:
  214. doAssert copySign(10.0, 1.0) == 10.0
  215. doAssert copySign(10.0, -1.0) == -10.0
  216. doAssert copySign(-Inf, -0.0) == -Inf
  217. doAssert copySign(NaN, 1.0).isNaN
  218. doAssert copySign(1.0, copySign(NaN, -1.0)) == -1.0
  219. # TODO: use signbit for examples
  220. when defined(js):
  221. let uintBuffer = toBitsImpl(y)
  222. let sgn = (uintBuffer[1] shr 31) != 0
  223. result = jsSetSign(x, sgn)
  224. else:
  225. when nimvm: # not exact but we have a vmops for recent enough nim
  226. if y > 0.0 or (y == 0.0 and 1.0 / y > 0.0):
  227. result = abs(x)
  228. elif y <= 0.0:
  229. result = -abs(x)
  230. else: # must be NaN
  231. result = abs(x)
  232. else: result = c_copysign(x, y)
  233. func classify*(x: float): FloatClass =
  234. ## Classifies a floating point value.
  235. ##
  236. ## Returns `x`'s class as specified by the `FloatClass enum<#FloatClass>`_.
  237. ## Doesn't work with `--passc:-ffast-math`.
  238. runnableExamples:
  239. doAssert classify(0.3) == fcNormal
  240. doAssert classify(0.0) == fcZero
  241. doAssert classify(0.3 / 0.0) == fcInf
  242. doAssert classify(-0.3 / 0.0) == fcNegInf
  243. doAssert classify(5.0e-324) == fcSubnormal
  244. # JavaScript and most C compilers have no classify:
  245. if x == 0.0:
  246. if 1.0 / x == Inf:
  247. return fcZero
  248. else:
  249. return fcNegZero
  250. if x * 0.5 == x:
  251. if x > 0.0: return fcInf
  252. else: return fcNegInf
  253. if x != x: return fcNan
  254. if abs(x) < MinFloatNormal:
  255. return fcSubnormal
  256. return fcNormal
  257. func almostEqual*[T: SomeFloat](x, y: T; unitsInLastPlace: Natural = 4): bool {.
  258. since: (1, 5), inline.} =
  259. ## Checks if two float values are almost equal, using the
  260. ## [machine epsilon](https://en.wikipedia.org/wiki/Machine_epsilon).
  261. ##
  262. ## `unitsInLastPlace` is the max number of
  263. ## [units in the last place](https://en.wikipedia.org/wiki/Unit_in_the_last_place)
  264. ## difference tolerated when comparing two numbers. The larger the value, the
  265. ## more error is allowed. A `0` value means that two numbers must be exactly the
  266. ## same to be considered equal.
  267. ##
  268. ## The machine epsilon has to be scaled to the magnitude of the values used
  269. ## and multiplied by the desired precision in ULPs unless the difference is
  270. ## subnormal.
  271. ##
  272. # taken from: https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon
  273. runnableExamples:
  274. doAssert almostEqual(PI, 3.14159265358979)
  275. doAssert almostEqual(Inf, Inf)
  276. doAssert not almostEqual(NaN, NaN)
  277. if x == y:
  278. # short circuit exact equality -- needed to catch two infinities of
  279. # the same sign. And perhaps speeds things up a bit sometimes.
  280. return true
  281. let diff = abs(x - y)
  282. result = diff <= epsilon(T) * abs(x + y) * T(unitsInLastPlace) or
  283. diff < minimumPositiveValue(T)
  284. func isPowerOfTwo*(x: int): bool =
  285. ## Returns `true`, if `x` is a power of two, `false` otherwise.
  286. ##
  287. ## Zero and negative numbers are not a power of two.
  288. ##
  289. ## **See also:**
  290. ## * `nextPowerOfTwo func <#nextPowerOfTwo,int>`_
  291. runnableExamples:
  292. doAssert isPowerOfTwo(16)
  293. doAssert not isPowerOfTwo(5)
  294. doAssert not isPowerOfTwo(0)
  295. doAssert not isPowerOfTwo(-16)
  296. return (x > 0) and ((x and (x - 1)) == 0)
  297. func nextPowerOfTwo*(x: int): int =
  298. ## Returns `x` rounded up to the nearest power of two.
  299. ##
  300. ## Zero and negative numbers get rounded up to 1.
  301. ##
  302. ## **See also:**
  303. ## * `isPowerOfTwo func <#isPowerOfTwo,int>`_
  304. runnableExamples:
  305. doAssert nextPowerOfTwo(16) == 16
  306. doAssert nextPowerOfTwo(5) == 8
  307. doAssert nextPowerOfTwo(0) == 1
  308. doAssert nextPowerOfTwo(-16) == 1
  309. result = x - 1
  310. when defined(cpu64):
  311. result = result or (result shr 32)
  312. when sizeof(int) > 2:
  313. result = result or (result shr 16)
  314. when sizeof(int) > 1:
  315. result = result or (result shr 8)
  316. result = result or (result shr 4)
  317. result = result or (result shr 2)
  318. result = result or (result shr 1)
  319. result += 1 + ord(x <= 0)
  320. when not defined(js): # C
  321. func sqrt*(x: float32): float32 {.importc: "sqrtf", header: "<math.h>".}
  322. func sqrt*(x: float64): float64 {.importc: "sqrt", header: "<math.h>".} =
  323. ## Computes the square root of `x`.
  324. ##
  325. ## **See also:**
  326. ## * `cbrt func <#cbrt,float64>`_ for the cube root
  327. runnableExamples:
  328. doAssert almostEqual(sqrt(4.0), 2.0)
  329. doAssert almostEqual(sqrt(1.44), 1.2)
  330. func cbrt*(x: float32): float32 {.importc: "cbrtf", header: "<math.h>".}
  331. func cbrt*(x: float64): float64 {.importc: "cbrt", header: "<math.h>".} =
  332. ## Computes the cube root of `x`.
  333. ##
  334. ## **See also:**
  335. ## * `sqrt func <#sqrt,float64>`_ for the square root
  336. runnableExamples:
  337. doAssert almostEqual(cbrt(8.0), 2.0)
  338. doAssert almostEqual(cbrt(2.197), 1.3)
  339. doAssert almostEqual(cbrt(-27.0), -3.0)
  340. func ln*(x: float32): float32 {.importc: "logf", header: "<math.h>".}
  341. func ln*(x: float64): float64 {.importc: "log", header: "<math.h>".} =
  342. ## Computes the [natural logarithm](https://en.wikipedia.org/wiki/Natural_logarithm)
  343. ## of `x`.
  344. ##
  345. ## **See also:**
  346. ## * `log func <#log,T,T>`_
  347. ## * `log10 func <#log10,float64>`_
  348. ## * `log2 func <#log2,float64>`_
  349. ## * `exp func <#exp,float64>`_
  350. runnableExamples:
  351. doAssert almostEqual(ln(exp(4.0)), 4.0)
  352. doAssert almostEqual(ln(1.0), 0.0)
  353. doAssert almostEqual(ln(0.0), -Inf)
  354. doAssert ln(-7.0).isNaN
  355. else: # JS
  356. func sqrt*(x: float32): float32 {.importc: "Math.sqrt", nodecl.}
  357. func sqrt*(x: float64): float64 {.importc: "Math.sqrt", nodecl.}
  358. func cbrt*(x: float32): float32 {.importc: "Math.cbrt", nodecl.}
  359. func cbrt*(x: float64): float64 {.importc: "Math.cbrt", nodecl.}
  360. func ln*(x: float32): float32 {.importc: "Math.log", nodecl.}
  361. func ln*(x: float64): float64 {.importc: "Math.log", nodecl.}
  362. func log*[T: SomeFloat](x, base: T): T =
  363. ## Computes the logarithm of `x` to base `base`.
  364. ##
  365. ## **See also:**
  366. ## * `ln func <#ln,float64>`_
  367. ## * `log10 func <#log10,float64>`_
  368. ## * `log2 func <#log2,float64>`_
  369. runnableExamples:
  370. doAssert almostEqual(log(9.0, 3.0), 2.0)
  371. doAssert almostEqual(log(0.0, 2.0), -Inf)
  372. doAssert log(-7.0, 4.0).isNaN
  373. doAssert log(8.0, -2.0).isNaN
  374. ln(x) / ln(base)
  375. when not defined(js): # C
  376. func log10*(x: float32): float32 {.importc: "log10f", header: "<math.h>".}
  377. func log10*(x: float64): float64 {.importc: "log10", header: "<math.h>".} =
  378. ## Computes the common logarithm (base 10) of `x`.
  379. ##
  380. ## **See also:**
  381. ## * `ln func <#ln,float64>`_
  382. ## * `log func <#log,T,T>`_
  383. ## * `log2 func <#log2,float64>`_
  384. runnableExamples:
  385. doAssert almostEqual(log10(100.0) , 2.0)
  386. doAssert almostEqual(log10(0.0), -Inf)
  387. doAssert log10(-100.0).isNaN
  388. func exp*(x: float32): float32 {.importc: "expf", header: "<math.h>".}
  389. func exp*(x: float64): float64 {.importc: "exp", header: "<math.h>".} =
  390. ## Computes the exponential function of `x` (`e^x`).
  391. ##
  392. ## **See also:**
  393. ## * `ln func <#ln,float64>`_
  394. runnableExamples:
  395. doAssert almostEqual(exp(1.0), E)
  396. doAssert almostEqual(ln(exp(4.0)), 4.0)
  397. doAssert almostEqual(exp(0.0), 1.0)
  398. func sin*(x: float32): float32 {.importc: "sinf", header: "<math.h>".}
  399. func sin*(x: float64): float64 {.importc: "sin", header: "<math.h>".} =
  400. ## Computes the sine of `x`.
  401. ##
  402. ## **See also:**
  403. ## * `arcsin func <#arcsin,float64>`_
  404. runnableExamples:
  405. doAssert almostEqual(sin(PI / 6), 0.5)
  406. doAssert almostEqual(sin(degToRad(90.0)), 1.0)
  407. func cos*(x: float32): float32 {.importc: "cosf", header: "<math.h>".}
  408. func cos*(x: float64): float64 {.importc: "cos", header: "<math.h>".} =
  409. ## Computes the cosine of `x`.
  410. ##
  411. ## **See also:**
  412. ## * `arccos func <#arccos,float64>`_
  413. runnableExamples:
  414. doAssert almostEqual(cos(2 * PI), 1.0)
  415. doAssert almostEqual(cos(degToRad(60.0)), 0.5)
  416. func tan*(x: float32): float32 {.importc: "tanf", header: "<math.h>".}
  417. func tan*(x: float64): float64 {.importc: "tan", header: "<math.h>".} =
  418. ## Computes the tangent of `x`.
  419. ##
  420. ## **See also:**
  421. ## * `arctan func <#arctan,float64>`_
  422. runnableExamples:
  423. doAssert almostEqual(tan(degToRad(45.0)), 1.0)
  424. doAssert almostEqual(tan(PI / 4), 1.0)
  425. func sinh*(x: float32): float32 {.importc: "sinhf", header: "<math.h>".}
  426. func sinh*(x: float64): float64 {.importc: "sinh", header: "<math.h>".} =
  427. ## Computes the [hyperbolic sine](https://en.wikipedia.org/wiki/Hyperbolic_function#Definitions) of `x`.
  428. ##
  429. ## **See also:**
  430. ## * `arcsinh func <#arcsinh,float64>`_
  431. runnableExamples:
  432. doAssert almostEqual(sinh(0.0), 0.0)
  433. doAssert almostEqual(sinh(1.0), 1.175201193643801)
  434. func cosh*(x: float32): float32 {.importc: "coshf", header: "<math.h>".}
  435. func cosh*(x: float64): float64 {.importc: "cosh", header: "<math.h>".} =
  436. ## Computes the [hyperbolic cosine](https://en.wikipedia.org/wiki/Hyperbolic_function#Definitions) of `x`.
  437. ##
  438. ## **See also:**
  439. ## * `arccosh func <#arccosh,float64>`_
  440. runnableExamples:
  441. doAssert almostEqual(cosh(0.0), 1.0)
  442. doAssert almostEqual(cosh(1.0), 1.543080634815244)
  443. func tanh*(x: float32): float32 {.importc: "tanhf", header: "<math.h>".}
  444. func tanh*(x: float64): float64 {.importc: "tanh", header: "<math.h>".} =
  445. ## Computes the [hyperbolic tangent](https://en.wikipedia.org/wiki/Hyperbolic_function#Definitions) of `x`.
  446. ##
  447. ## **See also:**
  448. ## * `arctanh func <#arctanh,float64>`_
  449. runnableExamples:
  450. doAssert almostEqual(tanh(0.0), 0.0)
  451. doAssert almostEqual(tanh(1.0), 0.7615941559557649)
  452. func arcsin*(x: float32): float32 {.importc: "asinf", header: "<math.h>".}
  453. func arcsin*(x: float64): float64 {.importc: "asin", header: "<math.h>".} =
  454. ## Computes the arc sine of `x`.
  455. ##
  456. ## **See also:**
  457. ## * `sin func <#sin,float64>`_
  458. runnableExamples:
  459. doAssert almostEqual(radToDeg(arcsin(0.0)), 0.0)
  460. doAssert almostEqual(radToDeg(arcsin(1.0)), 90.0)
  461. func arccos*(x: float32): float32 {.importc: "acosf", header: "<math.h>".}
  462. func arccos*(x: float64): float64 {.importc: "acos", header: "<math.h>".} =
  463. ## Computes the arc cosine of `x`.
  464. ##
  465. ## **See also:**
  466. ## * `cos func <#cos,float64>`_
  467. runnableExamples:
  468. doAssert almostEqual(radToDeg(arccos(0.0)), 90.0)
  469. doAssert almostEqual(radToDeg(arccos(1.0)), 0.0)
  470. func arctan*(x: float32): float32 {.importc: "atanf", header: "<math.h>".}
  471. func arctan*(x: float64): float64 {.importc: "atan", header: "<math.h>".} =
  472. ## Calculate the arc tangent of `x`.
  473. ##
  474. ## **See also:**
  475. ## * `arctan2 func <#arctan2,float64,float64>`_
  476. ## * `tan func <#tan,float64>`_
  477. runnableExamples:
  478. doAssert almostEqual(arctan(1.0), 0.7853981633974483)
  479. doAssert almostEqual(radToDeg(arctan(1.0)), 45.0)
  480. func arctan2*(y, x: float32): float32 {.importc: "atan2f", header: "<math.h>".}
  481. func arctan2*(y, x: float64): float64 {.importc: "atan2", header: "<math.h>".} =
  482. ## Calculate the arc tangent of `y/x`.
  483. ##
  484. ## It produces correct results even when the resulting angle is near
  485. ## `PI/2` or `-PI/2` (`x` near 0).
  486. ##
  487. ## **See also:**
  488. ## * `arctan func <#arctan,float64>`_
  489. runnableExamples:
  490. doAssert almostEqual(arctan2(1.0, 0.0), PI / 2.0)
  491. doAssert almostEqual(radToDeg(arctan2(1.0, 0.0)), 90.0)
  492. func arcsinh*(x: float32): float32 {.importc: "asinhf", header: "<math.h>".}
  493. func arcsinh*(x: float64): float64 {.importc: "asinh", header: "<math.h>".}
  494. ## Computes the inverse hyperbolic sine of `x`.
  495. ##
  496. ## **See also:**
  497. ## * `sinh func <#sinh,float64>`_
  498. func arccosh*(x: float32): float32 {.importc: "acoshf", header: "<math.h>".}
  499. func arccosh*(x: float64): float64 {.importc: "acosh", header: "<math.h>".}
  500. ## Computes the inverse hyperbolic cosine of `x`.
  501. ##
  502. ## **See also:**
  503. ## * `cosh func <#cosh,float64>`_
  504. func arctanh*(x: float32): float32 {.importc: "atanhf", header: "<math.h>".}
  505. func arctanh*(x: float64): float64 {.importc: "atanh", header: "<math.h>".}
  506. ## Computes the inverse hyperbolic tangent of `x`.
  507. ##
  508. ## **See also:**
  509. ## * `tanh func <#tanh,float64>`_
  510. else: # JS
  511. func log10*(x: float32): float32 {.importc: "Math.log10", nodecl.}
  512. func log10*(x: float64): float64 {.importc: "Math.log10", nodecl.}
  513. func log2*(x: float32): float32 {.importc: "Math.log2", nodecl.}
  514. func log2*(x: float64): float64 {.importc: "Math.log2", nodecl.}
  515. func exp*(x: float32): float32 {.importc: "Math.exp", nodecl.}
  516. func exp*(x: float64): float64 {.importc: "Math.exp", nodecl.}
  517. func sin*[T: float32|float64](x: T): T {.importc: "Math.sin", nodecl.}
  518. func cos*[T: float32|float64](x: T): T {.importc: "Math.cos", nodecl.}
  519. func tan*[T: float32|float64](x: T): T {.importc: "Math.tan", nodecl.}
  520. func sinh*[T: float32|float64](x: T): T {.importc: "Math.sinh", nodecl.}
  521. func cosh*[T: float32|float64](x: T): T {.importc: "Math.cosh", nodecl.}
  522. func tanh*[T: float32|float64](x: T): T {.importc: "Math.tanh", nodecl.}
  523. func arcsin*[T: float32|float64](x: T): T {.importc: "Math.asin", nodecl.}
  524. # keep this as generic or update test in `tvmops.nim` to make sure we
  525. # keep testing that generic importc procs work
  526. func arccos*[T: float32|float64](x: T): T {.importc: "Math.acos", nodecl.}
  527. func arctan*[T: float32|float64](x: T): T {.importc: "Math.atan", nodecl.}
  528. func arctan2*[T: float32|float64](y, x: T): T {.importc: "Math.atan2", nodecl.}
  529. func arcsinh*[T: float32|float64](x: T): T {.importc: "Math.asinh", nodecl.}
  530. func arccosh*[T: float32|float64](x: T): T {.importc: "Math.acosh", nodecl.}
  531. func arctanh*[T: float32|float64](x: T): T {.importc: "Math.atanh", nodecl.}
  532. func cot*[T: float32|float64](x: T): T = 1.0 / tan(x)
  533. ## Computes the cotangent of `x` (`1/tan(x)`).
  534. func sec*[T: float32|float64](x: T): T = 1.0 / cos(x)
  535. ## Computes the secant of `x` (`1/cos(x)`).
  536. func csc*[T: float32|float64](x: T): T = 1.0 / sin(x)
  537. ## Computes the cosecant of `x` (`1/sin(x)`).
  538. func coth*[T: float32|float64](x: T): T = 1.0 / tanh(x)
  539. ## Computes the hyperbolic cotangent of `x` (`1/tanh(x)`).
  540. func sech*[T: float32|float64](x: T): T = 1.0 / cosh(x)
  541. ## Computes the hyperbolic secant of `x` (`1/cosh(x)`).
  542. func csch*[T: float32|float64](x: T): T = 1.0 / sinh(x)
  543. ## Computes the hyperbolic cosecant of `x` (`1/sinh(x)`).
  544. func arccot*[T: float32|float64](x: T): T = arctan(1.0 / x)
  545. ## Computes the inverse cotangent of `x` (`arctan(1/x)`).
  546. func arcsec*[T: float32|float64](x: T): T = arccos(1.0 / x)
  547. ## Computes the inverse secant of `x` (`arccos(1/x)`).
  548. func arccsc*[T: float32|float64](x: T): T = arcsin(1.0 / x)
  549. ## Computes the inverse cosecant of `x` (`arcsin(1/x)`).
  550. func arccoth*[T: float32|float64](x: T): T = arctanh(1.0 / x)
  551. ## Computes the inverse hyperbolic cotangent of `x` (`arctanh(1/x)`).
  552. func arcsech*[T: float32|float64](x: T): T = arccosh(1.0 / x)
  553. ## Computes the inverse hyperbolic secant of `x` (`arccosh(1/x)`).
  554. func arccsch*[T: float32|float64](x: T): T = arcsinh(1.0 / x)
  555. ## Computes the inverse hyperbolic cosecant of `x` (`arcsinh(1/x)`).
  556. const windowsCC89 = defined(windows) and defined(bcc)
  557. when not defined(js): # C
  558. func hypot*(x, y: float32): float32 {.importc: "hypotf", header: "<math.h>".}
  559. func hypot*(x, y: float64): float64 {.importc: "hypot", header: "<math.h>".} =
  560. ## Computes the length of the hypotenuse of a right-angle triangle with
  561. ## `x` as its base and `y` as its height. Equivalent to `sqrt(x*x + y*y)`.
  562. runnableExamples:
  563. doAssert almostEqual(hypot(3.0, 4.0), 5.0)
  564. func pow*(x, y: float32): float32 {.importc: "powf", header: "<math.h>".}
  565. func pow*(x, y: float64): float64 {.importc: "pow", header: "<math.h>".} =
  566. ## Computes `x` raised to the power of `y`.
  567. ##
  568. ## To compute the power between integers (e.g. 2^6),
  569. ## use the `^ func <#^,T,Natural>`_.
  570. ##
  571. ## **See also:**
  572. ## * `^ func <#^,T,Natural>`_
  573. ## * `sqrt func <#sqrt,float64>`_
  574. ## * `cbrt func <#cbrt,float64>`_
  575. runnableExamples:
  576. doAssert almostEqual(pow(100, 1.5), 1000.0)
  577. doAssert almostEqual(pow(16.0, 0.5), 4.0)
  578. # TODO: add C89 version on windows
  579. when not windowsCC89:
  580. func erf*(x: float32): float32 {.importc: "erff", header: "<math.h>".}
  581. func erf*(x: float64): float64 {.importc: "erf", header: "<math.h>".}
  582. ## Computes the [error function](https://en.wikipedia.org/wiki/Error_function) for `x`.
  583. ##
  584. ## **Note:** Not available for the JS backend.
  585. func erfc*(x: float32): float32 {.importc: "erfcf", header: "<math.h>".}
  586. func erfc*(x: float64): float64 {.importc: "erfc", header: "<math.h>".}
  587. ## Computes the [complementary error function](https://en.wikipedia.org/wiki/Error_function#Complementary_error_function) for `x`.
  588. ##
  589. ## **Note:** Not available for the JS backend.
  590. func gamma*(x: float32): float32 {.importc: "tgammaf", header: "<math.h>".}
  591. func gamma*(x: float64): float64 {.importc: "tgamma", header: "<math.h>".} =
  592. ## Computes the [gamma function](https://en.wikipedia.org/wiki/Gamma_function) for `x`.
  593. ##
  594. ## **Note:** Not available for the JS backend.
  595. ##
  596. ## **See also:**
  597. ## * `lgamma func <#lgamma,float64>`_ for the natural logarithm of the gamma function
  598. runnableExamples:
  599. doAssert almostEqual(gamma(1.0), 1.0)
  600. doAssert almostEqual(gamma(4.0), 6.0)
  601. doAssert almostEqual(gamma(11.0), 3628800.0)
  602. func lgamma*(x: float32): float32 {.importc: "lgammaf", header: "<math.h>".}
  603. func lgamma*(x: float64): float64 {.importc: "lgamma", header: "<math.h>".} =
  604. ## Computes the natural logarithm of the gamma function for `x`.
  605. ##
  606. ## **Note:** Not available for the JS backend.
  607. ##
  608. ## **See also:**
  609. ## * `gamma func <#gamma,float64>`_ for gamma function
  610. func floor*(x: float32): float32 {.importc: "floorf", header: "<math.h>".}
  611. func floor*(x: float64): float64 {.importc: "floor", header: "<math.h>".} =
  612. ## Computes the floor function (i.e. the largest integer not greater than `x`).
  613. ##
  614. ## **See also:**
  615. ## * `ceil func <#ceil,float64>`_
  616. ## * `round func <#round,float64>`_
  617. ## * `trunc func <#trunc,float64>`_
  618. runnableExamples:
  619. doAssert floor(2.1) == 2.0
  620. doAssert floor(2.9) == 2.0
  621. doAssert floor(-3.5) == -4.0
  622. func ceil*(x: float32): float32 {.importc: "ceilf", header: "<math.h>".}
  623. func ceil*(x: float64): float64 {.importc: "ceil", header: "<math.h>".} =
  624. ## Computes the ceiling function (i.e. the smallest integer not smaller
  625. ## than `x`).
  626. ##
  627. ## **See also:**
  628. ## * `floor func <#floor,float64>`_
  629. ## * `round func <#round,float64>`_
  630. ## * `trunc func <#trunc,float64>`_
  631. runnableExamples:
  632. doAssert ceil(2.1) == 3.0
  633. doAssert ceil(2.9) == 3.0
  634. doAssert ceil(-2.1) == -2.0
  635. when windowsCC89:
  636. # MSVC 2010 don't have trunc/truncf
  637. # this implementation was inspired by Go-lang Math.Trunc
  638. func truncImpl(f: float64): float64 =
  639. const
  640. mask: uint64 = 0x7FF
  641. shift: uint64 = 64 - 12
  642. bias: uint64 = 0x3FF
  643. if f < 1:
  644. if f < 0: return -truncImpl(-f)
  645. elif f == 0: return f # Return -0 when f == -0
  646. else: return 0
  647. var x = cast[uint64](f)
  648. let e = (x shr shift) and mask - bias
  649. # Keep the top 12+e bits, the integer part; clear the rest.
  650. if e < 64 - 12:
  651. x = x and (not (1'u64 shl (64'u64 - 12'u64 - e) - 1'u64))
  652. result = cast[float64](x)
  653. func truncImpl(f: float32): float32 =
  654. const
  655. mask: uint32 = 0xFF
  656. shift: uint32 = 32 - 9
  657. bias: uint32 = 0x7F
  658. if f < 1:
  659. if f < 0: return -truncImpl(-f)
  660. elif f == 0: return f # Return -0 when f == -0
  661. else: return 0
  662. var x = cast[uint32](f)
  663. let e = (x shr shift) and mask - bias
  664. # Keep the top 9+e bits, the integer part; clear the rest.
  665. if e < 32 - 9:
  666. x = x and (not (1'u32 shl (32'u32 - 9'u32 - e) - 1'u32))
  667. result = cast[float32](x)
  668. func trunc*(x: float64): float64 =
  669. if classify(x) in {fcZero, fcNegZero, fcNan, fcInf, fcNegInf}: return x
  670. result = truncImpl(x)
  671. func trunc*(x: float32): float32 =
  672. if classify(x) in {fcZero, fcNegZero, fcNan, fcInf, fcNegInf}: return x
  673. result = truncImpl(x)
  674. func round*[T: float32|float64](x: T): T =
  675. ## Windows compilers prior to MSVC 2012 do not implement 'round',
  676. ## 'roundl' or 'roundf'.
  677. result = if x < 0.0: ceil(x - T(0.5)) else: floor(x + T(0.5))
  678. else:
  679. func round*(x: float32): float32 {.importc: "roundf", header: "<math.h>".}
  680. func round*(x: float64): float64 {.importc: "round", header: "<math.h>".} =
  681. ## Rounds a float to zero decimal places.
  682. ##
  683. ## Used internally by the `round func <#round,T,int>`_
  684. ## when the specified number of places is 0.
  685. ##
  686. ## **See also:**
  687. ## * `round func <#round,T,int>`_ for rounding to the specific
  688. ## number of decimal places
  689. ## * `floor func <#floor,float64>`_
  690. ## * `ceil func <#ceil,float64>`_
  691. ## * `trunc func <#trunc,float64>`_
  692. runnableExamples:
  693. doAssert round(3.4) == 3.0
  694. doAssert round(3.5) == 4.0
  695. doAssert round(4.5) == 5.0
  696. func trunc*(x: float32): float32 {.importc: "truncf", header: "<math.h>".}
  697. func trunc*(x: float64): float64 {.importc: "trunc", header: "<math.h>".} =
  698. ## Truncates `x` to the decimal point.
  699. ##
  700. ## **See also:**
  701. ## * `floor func <#floor,float64>`_
  702. ## * `ceil func <#ceil,float64>`_
  703. ## * `round func <#round,float64>`_
  704. runnableExamples:
  705. doAssert trunc(PI) == 3.0
  706. doAssert trunc(-1.85) == -1.0
  707. func `mod`*(x, y: float32): float32 {.importc: "fmodf", header: "<math.h>".}
  708. func `mod`*(x, y: float64): float64 {.importc: "fmod", header: "<math.h>".} =
  709. ## Computes the modulo operation for float values (the remainder of `x` divided by `y`).
  710. ##
  711. ## **See also:**
  712. ## * `floorMod func <#floorMod,T,T>`_ for Python-like (`%` operator) behavior
  713. runnableExamples:
  714. doAssert 6.5 mod 2.5 == 1.5
  715. doAssert -6.5 mod 2.5 == -1.5
  716. doAssert 6.5 mod -2.5 == 1.5
  717. doAssert -6.5 mod -2.5 == -1.5
  718. else: # JS
  719. func hypot*(x, y: float32): float32 {.importc: "Math.hypot", varargs, nodecl.}
  720. func hypot*(x, y: float64): float64 {.importc: "Math.hypot", varargs, nodecl.}
  721. func pow*(x, y: float32): float32 {.importc: "Math.pow", nodecl.}
  722. func pow*(x, y: float64): float64 {.importc: "Math.pow", nodecl.}
  723. func floor*(x: float32): float32 {.importc: "Math.floor", nodecl.}
  724. func floor*(x: float64): float64 {.importc: "Math.floor", nodecl.}
  725. func ceil*(x: float32): float32 {.importc: "Math.ceil", nodecl.}
  726. func ceil*(x: float64): float64 {.importc: "Math.ceil", nodecl.}
  727. when (NimMajor, NimMinor) < (1, 5) or defined(nimLegacyJsRound):
  728. func round*(x: float): float {.importc: "Math.round", nodecl.}
  729. else:
  730. func jsRound(x: float): float {.importc: "Math.round", nodecl.}
  731. func round*[T: float64 | float32](x: T): T =
  732. if x >= 0: result = jsRound(x)
  733. else:
  734. result = ceil(x)
  735. if result - x >= T(0.5):
  736. result -= T(1.0)
  737. func trunc*(x: float32): float32 {.importc: "Math.trunc", nodecl.}
  738. func trunc*(x: float64): float64 {.importc: "Math.trunc", nodecl.}
  739. func `mod`*(x, y: float32): float32 {.importjs: "(# % #)".}
  740. func `mod`*(x, y: float64): float64 {.importjs: "(# % #)".} =
  741. ## Computes the modulo operation for float values (the remainder of `x` divided by `y`).
  742. runnableExamples:
  743. doAssert 6.5 mod 2.5 == 1.5
  744. doAssert -6.5 mod 2.5 == -1.5
  745. doAssert 6.5 mod -2.5 == 1.5
  746. doAssert -6.5 mod -2.5 == -1.5
  747. func divmod*[T:SomeInteger](num, denom: T): (T, T) =
  748. runnableExamples:
  749. doAssert divmod(5, 2) == (2, 1)
  750. doAssert divmod(5, -3) == (-1, 2)
  751. result[0] = num div denom
  752. result[1] = num mod denom
  753. func round*[T: float32|float64](x: T, places: int): T =
  754. ## Decimal rounding on a binary floating point number.
  755. ##
  756. ## This function is NOT reliable. Floating point numbers cannot hold
  757. ## non integer decimals precisely. If `places` is 0 (or omitted),
  758. ## round to the nearest integral value following normal mathematical
  759. ## rounding rules (e.g. `round(54.5) -> 55.0`). If `places` is
  760. ## greater than 0, round to the given number of decimal places,
  761. ## e.g. `round(54.346, 2) -> 54.350000000000001421…`. If `places` is negative, round
  762. ## to the left of the decimal place, e.g. `round(537.345, -1) -> 540.0`.
  763. runnableExamples:
  764. doAssert round(PI, 2) == 3.14
  765. doAssert round(PI, 4) == 3.1416
  766. if places == 0:
  767. result = round(x)
  768. else:
  769. var mult = pow(10.0, T(places))
  770. result = round(x * mult) / mult
  771. func floorDiv*[T: SomeInteger](x, y: T): T =
  772. ## Floor division is conceptually defined as `floor(x / y)`.
  773. ##
  774. ## This is different from the `system.div <system.html#div,int,int>`_
  775. ## operator, which is defined as `trunc(x / y)`.
  776. ## That is, `div` rounds towards `0` and `floorDiv` rounds down.
  777. ##
  778. ## **See also:**
  779. ## * `system.div proc <system.html#div,int,int>`_ for integer division
  780. ## * `floorMod func <#floorMod,T,T>`_ for Python-like (`%` operator) behavior
  781. runnableExamples:
  782. doAssert floorDiv( 13, 3) == 4
  783. doAssert floorDiv(-13, 3) == -5
  784. doAssert floorDiv( 13, -3) == -5
  785. doAssert floorDiv(-13, -3) == 4
  786. result = x div y
  787. let r = x mod y
  788. if (r > 0 and y < 0) or (r < 0 and y > 0): result.dec 1
  789. func floorMod*[T: SomeNumber](x, y: T): T =
  790. ## Floor modulo is conceptually defined as `x - (floorDiv(x, y) * y)`.
  791. ##
  792. ## This func behaves the same as the `%` operator in Python.
  793. ##
  794. ## **See also:**
  795. ## * `mod func <#mod,float64,float64>`_
  796. ## * `floorDiv func <#floorDiv,T,T>`_
  797. runnableExamples:
  798. doAssert floorMod( 13, 3) == 1
  799. doAssert floorMod(-13, 3) == 2
  800. doAssert floorMod( 13, -3) == -2
  801. doAssert floorMod(-13, -3) == -1
  802. result = x mod y
  803. if (result > 0 and y < 0) or (result < 0 and y > 0): result += y
  804. func euclDiv*[T: SomeInteger](x, y: T): T {.since: (1, 5, 1).} =
  805. ## Returns euclidean division of `x` by `y`.
  806. runnableExamples:
  807. doAssert euclDiv(13, 3) == 4
  808. doAssert euclDiv(-13, 3) == -5
  809. doAssert euclDiv(13, -3) == -4
  810. doAssert euclDiv(-13, -3) == 5
  811. result = x div y
  812. if x mod y < 0:
  813. if y > 0:
  814. dec result
  815. else:
  816. inc result
  817. func euclMod*[T: SomeNumber](x, y: T): T {.since: (1, 5, 1).} =
  818. ## Returns euclidean modulo of `x` by `y`.
  819. ## `euclMod(x, y)` is non-negative.
  820. runnableExamples:
  821. doAssert euclMod(13, 3) == 1
  822. doAssert euclMod(-13, 3) == 2
  823. doAssert euclMod(13, -3) == 1
  824. doAssert euclMod(-13, -3) == 2
  825. result = x mod y
  826. if result < 0:
  827. result += abs(y)
  828. func ceilDiv*[T: SomeInteger](x, y: T): T {.inline, since: (1, 5, 1).} =
  829. ## Ceil division is conceptually defined as `ceil(x / y)`.
  830. ##
  831. ## Assumes `x >= 0` and `y > 0` (and `x + y - 1 <= high(T)` if T is SomeUnsignedInt).
  832. ##
  833. ## This is different from the `system.div <system.html#div,int,int>`_
  834. ## operator, which works like `trunc(x / y)`.
  835. ## That is, `div` rounds towards `0` and `ceilDiv` rounds up.
  836. ##
  837. ## This function has the above input limitation, because that allows the
  838. ## compiler to generate faster code and it is rarely used with
  839. ## negative values or unsigned integers close to `high(T)/2`.
  840. ## If you need a `ceilDiv` that works with any input, see:
  841. ## https://github.com/demotomohiro/divmath.
  842. ##
  843. ## **See also:**
  844. ## * `system.div proc <system.html#div,int,int>`_ for integer division
  845. ## * `floorDiv func <#floorDiv,T,T>`_ for integer division which rounds down.
  846. runnableExamples:
  847. assert ceilDiv(12, 3) == 4
  848. assert ceilDiv(13, 3) == 5
  849. when sizeof(T) == 8:
  850. type UT = uint64
  851. elif sizeof(T) == 4:
  852. type UT = uint32
  853. elif sizeof(T) == 2:
  854. type UT = uint16
  855. elif sizeof(T) == 1:
  856. type UT = uint8
  857. else:
  858. {.fatal: "Unsupported int type".}
  859. assert x >= 0 and y > 0
  860. when T is SomeUnsignedInt:
  861. assert x + y - 1 >= x
  862. # If the divisor is const, the backend C/C++ compiler generates code without a `div`
  863. # instruction, as it is slow on most CPUs.
  864. # If the divisor is a power of 2 and a const unsigned integer type, the
  865. # compiler generates faster code.
  866. # If the divisor is const and a signed integer, generated code becomes slower
  867. # than the code with unsigned integers, because division with signed integers
  868. # need to works for both positive and negative value without `idiv`/`sdiv`.
  869. # That is why this code convert parameters to unsigned.
  870. # This post contains a comparison of the performance of signed/unsigned integers:
  871. # https://github.com/nim-lang/Nim/pull/18596#issuecomment-894420984.
  872. # If signed integer arguments were not converted to unsigned integers,
  873. # `ceilDiv` wouldn't work for any positive signed integer value, because
  874. # `x + (y - 1)` can overflow.
  875. ((x.UT + (y.UT - 1.UT)) div y.UT).T
  876. func frexp*[T: float32|float64](x: T): tuple[frac: T, exp: int] {.inline.} =
  877. ## Splits `x` into a normalized fraction `frac` and an integral power of 2 `exp`,
  878. ## such that `abs(frac) in 0.5..<1` and `x == frac * 2 ^ exp`, except for special
  879. ## cases shown below.
  880. runnableExamples:
  881. doAssert frexp(8.0) == (0.5, 4)
  882. doAssert frexp(-8.0) == (-0.5, 4)
  883. doAssert frexp(0.0) == (0.0, 0)
  884. # special cases:
  885. when sizeof(int) == 8:
  886. doAssert frexp(-0.0).frac.signbit # signbit preserved for +-0
  887. doAssert frexp(Inf).frac == Inf # +- Inf preserved
  888. doAssert frexp(NaN).frac.isNaN
  889. when not defined(js):
  890. var exp: cint
  891. result.frac = c_frexp2(x, exp)
  892. result.exp = exp
  893. else:
  894. if x == 0.0:
  895. # reuse signbit implementation
  896. let uintBuffer = toBitsImpl(x)
  897. if (uintBuffer[1] shr 31) != 0:
  898. # x is -0.0
  899. result = (-0.0, 0)
  900. else:
  901. result = (0.0, 0)
  902. elif x < 0.0:
  903. result = frexp(-x)
  904. result.frac = -result.frac
  905. else:
  906. var ex = trunc(log2(x))
  907. result.exp = int(ex)
  908. result.frac = x / pow(2.0, ex)
  909. if abs(result.frac) >= 1:
  910. inc(result.exp)
  911. result.frac = result.frac / 2
  912. if result.exp == 1024 and result.frac == 0.0:
  913. result.frac = 0.99999999999999988898
  914. func frexp*[T: float32|float64](x: T, exponent: var int): T {.inline.} =
  915. ## Overload of `frexp` that calls `(result, exponent) = frexp(x)`.
  916. runnableExamples:
  917. var x: int
  918. doAssert frexp(5.0, x) == 0.625
  919. doAssert x == 3
  920. (result, exponent) = frexp(x)
  921. when not defined(js):
  922. when windowsCC89:
  923. # taken from Go-lang Math.Log2
  924. const ln2 = 0.693147180559945309417232121458176568075500134360255254120680009
  925. template log2Impl[T](x: T): T =
  926. var exp: int
  927. var frac = frexp(x, exp)
  928. # Make sure exact powers of two give an exact answer.
  929. # Don't depend on Log(0.5)*(1/Ln2)+exp being exactly exp-1.
  930. if frac == 0.5: return T(exp - 1)
  931. log10(frac) * (1 / ln2) + T(exp)
  932. func log2*(x: float32): float32 = log2Impl(x)
  933. func log2*(x: float64): float64 = log2Impl(x)
  934. ## Log2 returns the binary logarithm of x.
  935. ## The special cases are the same as for Log.
  936. else:
  937. func log2*(x: float32): float32 {.importc: "log2f", header: "<math.h>".}
  938. func log2*(x: float64): float64 {.importc: "log2", header: "<math.h>".} =
  939. ## Computes the binary logarithm (base 2) of `x`.
  940. ##
  941. ## **See also:**
  942. ## * `log func <#log,T,T>`_
  943. ## * `log10 func <#log10,float64>`_
  944. ## * `ln func <#ln,float64>`_
  945. runnableExamples:
  946. doAssert almostEqual(log2(8.0), 3.0)
  947. doAssert almostEqual(log2(1.0), 0.0)
  948. doAssert almostEqual(log2(0.0), -Inf)
  949. doAssert log2(-2.0).isNaN
  950. func splitDecimal*[T: float32|float64](x: T): tuple[intpart: T, floatpart: T] =
  951. ## Breaks `x` into an integer and a fractional part.
  952. ##
  953. ## Returns a tuple containing `intpart` and `floatpart`, representing
  954. ## the integer part and the fractional part, respectively.
  955. ##
  956. ## Both parts have the same sign as `x`. Analogous to the `modf`
  957. ## function in C.
  958. runnableExamples:
  959. doAssert splitDecimal(5.25) == (intpart: 5.0, floatpart: 0.25)
  960. doAssert splitDecimal(-2.73) == (intpart: -2.0, floatpart: -0.73)
  961. var
  962. absolute: T
  963. absolute = abs(x)
  964. result.intpart = floor(absolute)
  965. result.floatpart = absolute - result.intpart
  966. if x < 0:
  967. result.intpart = -result.intpart
  968. result.floatpart = -result.floatpart
  969. func degToRad*[T: float32|float64](d: T): T {.inline.} =
  970. ## Converts from degrees to radians.
  971. ##
  972. ## **See also:**
  973. ## * `radToDeg func <#radToDeg,T>`_
  974. runnableExamples:
  975. doAssert almostEqual(degToRad(180.0), PI)
  976. result = d * T(RadPerDeg)
  977. func radToDeg*[T: float32|float64](d: T): T {.inline.} =
  978. ## Converts from radians to degrees.
  979. ##
  980. ## **See also:**
  981. ## * `degToRad func <#degToRad,T>`_
  982. runnableExamples:
  983. doAssert almostEqual(radToDeg(2 * PI), 360.0)
  984. result = d / T(RadPerDeg)
  985. func sgn*[T: SomeNumber](x: T): int {.inline.} =
  986. ## Sign function.
  987. ##
  988. ## Returns:
  989. ## * `-1` for negative numbers and `NegInf`,
  990. ## * `1` for positive numbers and `Inf`,
  991. ## * `0` for positive zero, negative zero and `NaN`
  992. runnableExamples:
  993. doAssert sgn(5) == 1
  994. doAssert sgn(0) == 0
  995. doAssert sgn(-4.1) == -1
  996. ord(T(0) < x) - ord(x < T(0))
  997. {.pop.}
  998. {.pop.}
  999. func sum*[T](x: openArray[T]): T =
  1000. ## Computes the sum of the elements in `x`.
  1001. ##
  1002. ## If `x` is empty, 0 is returned.
  1003. ##
  1004. ## **See also:**
  1005. ## * `prod func <#prod,openArray[T]>`_
  1006. ## * `cumsum func <#cumsum,openArray[T]>`_
  1007. ## * `cumsummed func <#cumsummed,openArray[T]>`_
  1008. runnableExamples:
  1009. doAssert sum([1, 2, 3, 4]) == 10
  1010. doAssert sum([-4, 3, 5]) == 4
  1011. for i in items(x): result = result + i
  1012. func prod*[T](x: openArray[T]): T =
  1013. ## Computes the product of the elements in `x`.
  1014. ##
  1015. ## If `x` is empty, 1 is returned.
  1016. ##
  1017. ## **See also:**
  1018. ## * `sum func <#sum,openArray[T]>`_
  1019. ## * `fac func <#fac,int>`_
  1020. runnableExamples:
  1021. doAssert prod([1, 2, 3, 4]) == 24
  1022. doAssert prod([-4, 3, 5]) == -60
  1023. result = T(1)
  1024. for i in items(x): result = result * i
  1025. func cumsummed*[T](x: openArray[T]): seq[T] =
  1026. ## Returns the cumulative (aka prefix) summation of `x`.
  1027. ##
  1028. ## If `x` is empty, `@[]` is returned.
  1029. ##
  1030. ## **See also:**
  1031. ## * `sum func <#sum,openArray[T]>`_
  1032. ## * `cumsum func <#cumsum,openArray[T]>`_ for the in-place version
  1033. runnableExamples:
  1034. doAssert cumsummed([1, 2, 3, 4]) == @[1, 3, 6, 10]
  1035. let xLen = x.len
  1036. if xLen == 0:
  1037. return @[]
  1038. result.setLen(xLen)
  1039. result[0] = x[0]
  1040. for i in 1 ..< xLen: result[i] = result[i - 1] + x[i]
  1041. func cumsum*[T](x: var openArray[T]) =
  1042. ## Transforms `x` in-place (must be declared as `var`) into its
  1043. ## cumulative (aka prefix) summation.
  1044. ##
  1045. ## **See also:**
  1046. ## * `sum func <#sum,openArray[T]>`_
  1047. ## * `cumsummed func <#cumsummed,openArray[T]>`_ for a version which
  1048. ## returns a cumsummed sequence
  1049. runnableExamples:
  1050. var a = [1, 2, 3, 4]
  1051. cumsum(a)
  1052. doAssert a == @[1, 3, 6, 10]
  1053. for i in 1 ..< x.len: x[i] = x[i - 1] + x[i]
  1054. func `^`*[T: SomeNumber](x: T, y: Natural): T =
  1055. ## Computes `x` to the power of `y`.
  1056. ##
  1057. ## The exponent `y` must be non-negative, use
  1058. ## `pow <#pow,float64,float64>`_ for negative exponents.
  1059. ##
  1060. ## **See also:**
  1061. ## * `pow func <#pow,float64,float64>`_ for negative exponent or
  1062. ## floats
  1063. ## * `sqrt func <#sqrt,float64>`_
  1064. ## * `cbrt func <#cbrt,float64>`_
  1065. runnableExamples:
  1066. doAssert -3 ^ 0 == 1
  1067. doAssert -3 ^ 1 == -3
  1068. doAssert -3 ^ 2 == 9
  1069. case y
  1070. of 0: result = 1
  1071. of 1: result = x
  1072. of 2: result = x * x
  1073. of 3: result = x * x * x
  1074. else:
  1075. var (x, y) = (x, y)
  1076. result = 1
  1077. while true:
  1078. if (y and 1) != 0:
  1079. result *= x
  1080. y = y shr 1
  1081. if y == 0:
  1082. break
  1083. x *= x
  1084. func gcd*[T](x, y: T): T =
  1085. ## Computes the greatest common (positive) divisor of `x` and `y`.
  1086. ##
  1087. ## Note that for floats, the result cannot always be interpreted as
  1088. ## "greatest decimal `z` such that `z*N == x and z*M == y`
  1089. ## where N and M are positive integers".
  1090. ##
  1091. ## **See also:**
  1092. ## * `gcd func <#gcd,SomeInteger,SomeInteger>`_ for an integer version
  1093. ## * `lcm func <#lcm,T,T>`_
  1094. runnableExamples:
  1095. doAssert gcd(13.5, 9.0) == 4.5
  1096. var (x, y) = (x, y)
  1097. while y != 0:
  1098. x = x mod y
  1099. swap x, y
  1100. abs x
  1101. func gcd*(x, y: SomeInteger): SomeInteger =
  1102. ## Computes the greatest common (positive) divisor of `x` and `y`,
  1103. ## using the binary GCD (aka Stein's) algorithm.
  1104. ##
  1105. ## **See also:**
  1106. ## * `gcd func <#gcd,T,T>`_ for a float version
  1107. ## * `lcm func <#lcm,T,T>`_
  1108. runnableExamples:
  1109. doAssert gcd(12, 8) == 4
  1110. doAssert gcd(17, 63) == 1
  1111. when x is SomeSignedInt:
  1112. var x = abs(x)
  1113. else:
  1114. var x = x
  1115. when y is SomeSignedInt:
  1116. var y = abs(y)
  1117. else:
  1118. var y = y
  1119. if x == 0:
  1120. return y
  1121. if y == 0:
  1122. return x
  1123. let shift = countTrailingZeroBits(x or y)
  1124. y = y shr countTrailingZeroBits(y)
  1125. while x != 0:
  1126. x = x shr countTrailingZeroBits(x)
  1127. if y > x:
  1128. swap y, x
  1129. x -= y
  1130. y shl shift
  1131. func gcd*[T](x: openArray[T]): T {.since: (1, 1).} =
  1132. ## Computes the greatest common (positive) divisor of the elements of `x`.
  1133. ##
  1134. ## **See also:**
  1135. ## * `gcd func <#gcd,T,T>`_ for a version with two arguments
  1136. runnableExamples:
  1137. doAssert gcd(@[13.5, 9.0]) == 4.5
  1138. result = x[0]
  1139. for i in 1 ..< x.len:
  1140. result = gcd(result, x[i])
  1141. func lcm*[T](x, y: T): T =
  1142. ## Computes the least common multiple of `x` and `y`.
  1143. ##
  1144. ## **See also:**
  1145. ## * `gcd func <#gcd,T,T>`_
  1146. runnableExamples:
  1147. doAssert lcm(24, 30) == 120
  1148. doAssert lcm(13, 39) == 39
  1149. x div gcd(x, y) * y
  1150. func clamp*[T](val: T, bounds: Slice[T]): T {.since: (1, 5), inline.} =
  1151. ## Like `system.clamp`, but takes a slice, so you can easily clamp within a range.
  1152. runnableExamples:
  1153. assert clamp(10, 1 .. 5) == 5
  1154. assert clamp(1, 1 .. 3) == 1
  1155. type A = enum a0, a1, a2, a3, a4, a5
  1156. assert a1.clamp(a2..a4) == a2
  1157. assert clamp((3, 0), (1, 0) .. (2, 9)) == (2, 9)
  1158. doAssertRaises(AssertionDefect): discard clamp(1, 3..2) # invalid bounds
  1159. assert bounds.a <= bounds.b, $(bounds.a, bounds.b)
  1160. clamp(val, bounds.a, bounds.b)
  1161. func lcm*[T](x: openArray[T]): T {.since: (1, 1).} =
  1162. ## Computes the least common multiple of the elements of `x`.
  1163. ##
  1164. ## **See also:**
  1165. ## * `lcm func <#lcm,T,T>`_ for a version with two arguments
  1166. runnableExamples:
  1167. doAssert lcm(@[24, 30]) == 120
  1168. result = x[0]
  1169. for i in 1 ..< x.len:
  1170. result = lcm(result, x[i])