math.nim 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  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 std/[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) and not defined(macosx):
  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) or defined(nimscript): 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. {.emit: """
  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. runnableExamples:
  238. doAssert classify(0.3) == fcNormal
  239. doAssert classify(0.0) == fcZero
  240. doAssert classify(0.3 / 0.0) == fcInf
  241. doAssert classify(-0.3 / 0.0) == fcNegInf
  242. doAssert classify(5.0e-324) == fcSubnormal
  243. # JavaScript and most C compilers have no classify:
  244. if isNan(x): return fcNan
  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 abs(x) < MinFloatNormal:
  254. return fcSubnormal
  255. return fcNormal
  256. func almostEqual*[T: SomeFloat](x, y: T; unitsInLastPlace: Natural = 4): bool {.
  257. since: (1, 5), inline.} =
  258. ## Checks if two float values are almost equal, using the
  259. ## [machine epsilon](https://en.wikipedia.org/wiki/Machine_epsilon).
  260. ##
  261. ## `unitsInLastPlace` is the max number of
  262. ## [units in the last place](https://en.wikipedia.org/wiki/Unit_in_the_last_place)
  263. ## difference tolerated when comparing two numbers. The larger the value, the
  264. ## more error is allowed. A `0` value means that two numbers must be exactly the
  265. ## same to be considered equal.
  266. ##
  267. ## The machine epsilon has to be scaled to the magnitude of the values used
  268. ## and multiplied by the desired precision in ULPs unless the difference is
  269. ## subnormal.
  270. ##
  271. # taken from: https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon
  272. runnableExamples:
  273. doAssert almostEqual(PI, 3.14159265358979)
  274. doAssert almostEqual(Inf, Inf)
  275. doAssert not almostEqual(NaN, NaN)
  276. if x == y:
  277. # short circuit exact equality -- needed to catch two infinities of
  278. # the same sign. And perhaps speeds things up a bit sometimes.
  279. return true
  280. let diff = abs(x - y)
  281. result = diff <= epsilon(T) * abs(x + y) * T(unitsInLastPlace) or
  282. diff < minimumPositiveValue(T)
  283. func isPowerOfTwo*(x: int): bool =
  284. ## Returns `true`, if `x` is a power of two, `false` otherwise.
  285. ##
  286. ## Zero and negative numbers are not a power of two.
  287. ##
  288. ## **See also:**
  289. ## * `nextPowerOfTwo func <#nextPowerOfTwo,int>`_
  290. runnableExamples:
  291. doAssert isPowerOfTwo(16)
  292. doAssert not isPowerOfTwo(5)
  293. doAssert not isPowerOfTwo(0)
  294. doAssert not isPowerOfTwo(-16)
  295. return (x > 0) and ((x and (x - 1)) == 0)
  296. func nextPowerOfTwo*(x: int): int =
  297. ## Returns `x` rounded up to the nearest power of two.
  298. ##
  299. ## Zero and negative numbers get rounded up to 1.
  300. ##
  301. ## **See also:**
  302. ## * `isPowerOfTwo func <#isPowerOfTwo,int>`_
  303. runnableExamples:
  304. doAssert nextPowerOfTwo(16) == 16
  305. doAssert nextPowerOfTwo(5) == 8
  306. doAssert nextPowerOfTwo(0) == 1
  307. doAssert nextPowerOfTwo(-16) == 1
  308. result = x - 1
  309. when defined(cpu64):
  310. result = result or (result shr 32)
  311. when sizeof(int) > 2:
  312. result = result or (result shr 16)
  313. when sizeof(int) > 1:
  314. result = result or (result shr 8)
  315. result = result or (result shr 4)
  316. result = result or (result shr 2)
  317. result = result or (result shr 1)
  318. result += 1 + ord(x <= 0)
  319. when not defined(js): # C
  320. func sqrt*(x: float32): float32 {.importc: "sqrtf", header: "<math.h>".}
  321. func sqrt*(x: float64): float64 {.importc: "sqrt", header: "<math.h>".} =
  322. ## Computes the square root of `x`.
  323. ##
  324. ## **See also:**
  325. ## * `cbrt func <#cbrt,float64>`_ for the cube root
  326. runnableExamples:
  327. doAssert almostEqual(sqrt(4.0), 2.0)
  328. doAssert almostEqual(sqrt(1.44), 1.2)
  329. func cbrt*(x: float32): float32 {.importc: "cbrtf", header: "<math.h>".}
  330. func cbrt*(x: float64): float64 {.importc: "cbrt", header: "<math.h>".} =
  331. ## Computes the cube root of `x`.
  332. ##
  333. ## **See also:**
  334. ## * `sqrt func <#sqrt,float64>`_ for the square root
  335. runnableExamples:
  336. doAssert almostEqual(cbrt(8.0), 2.0)
  337. doAssert almostEqual(cbrt(2.197), 1.3)
  338. doAssert almostEqual(cbrt(-27.0), -3.0)
  339. func ln*(x: float32): float32 {.importc: "logf", header: "<math.h>".}
  340. func ln*(x: float64): float64 {.importc: "log", header: "<math.h>".} =
  341. ## Computes the [natural logarithm](https://en.wikipedia.org/wiki/Natural_logarithm)
  342. ## of `x`.
  343. ##
  344. ## **See also:**
  345. ## * `log func <#log,T,T>`_
  346. ## * `log10 func <#log10,float64>`_
  347. ## * `log2 func <#log2,float64>`_
  348. ## * `exp func <#exp,float64>`_
  349. runnableExamples:
  350. doAssert almostEqual(ln(exp(4.0)), 4.0)
  351. doAssert almostEqual(ln(1.0), 0.0)
  352. doAssert almostEqual(ln(0.0), -Inf)
  353. doAssert ln(-7.0).isNaN
  354. else: # JS
  355. func sqrt*(x: float32): float32 {.importc: "Math.sqrt", nodecl.}
  356. func sqrt*(x: float64): float64 {.importc: "Math.sqrt", nodecl.}
  357. func cbrt*(x: float32): float32 {.importc: "Math.cbrt", nodecl.}
  358. func cbrt*(x: float64): float64 {.importc: "Math.cbrt", nodecl.}
  359. func ln*(x: float32): float32 {.importc: "Math.log", nodecl.}
  360. func ln*(x: float64): float64 {.importc: "Math.log", nodecl.}
  361. func log*[T: SomeFloat](x, base: T): T =
  362. ## Computes the logarithm of `x` to base `base`.
  363. ##
  364. ## **See also:**
  365. ## * `ln func <#ln,float64>`_
  366. ## * `log10 func <#log10,float64>`_
  367. ## * `log2 func <#log2,float64>`_
  368. runnableExamples:
  369. doAssert almostEqual(log(9.0, 3.0), 2.0)
  370. doAssert almostEqual(log(0.0, 2.0), -Inf)
  371. doAssert log(-7.0, 4.0).isNaN
  372. doAssert log(8.0, -2.0).isNaN
  373. ln(x) / ln(base)
  374. when not defined(js): # C
  375. func log10*(x: float32): float32 {.importc: "log10f", header: "<math.h>".}
  376. func log10*(x: float64): float64 {.importc: "log10", header: "<math.h>".} =
  377. ## Computes the common logarithm (base 10) of `x`.
  378. ##
  379. ## **See also:**
  380. ## * `ln func <#ln,float64>`_
  381. ## * `log func <#log,T,T>`_
  382. ## * `log2 func <#log2,float64>`_
  383. runnableExamples:
  384. doAssert almostEqual(log10(100.0) , 2.0)
  385. doAssert almostEqual(log10(0.0), -Inf)
  386. doAssert log10(-100.0).isNaN
  387. func exp*(x: float32): float32 {.importc: "expf", header: "<math.h>".}
  388. func exp*(x: float64): float64 {.importc: "exp", header: "<math.h>".} =
  389. ## Computes the exponential function of `x` (`e^x`).
  390. ##
  391. ## **See also:**
  392. ## * `ln func <#ln,float64>`_
  393. runnableExamples:
  394. doAssert almostEqual(exp(1.0), E)
  395. doAssert almostEqual(ln(exp(4.0)), 4.0)
  396. doAssert almostEqual(exp(0.0), 1.0)
  397. func sin*(x: float32): float32 {.importc: "sinf", header: "<math.h>".}
  398. func sin*(x: float64): float64 {.importc: "sin", header: "<math.h>".} =
  399. ## Computes the sine of `x`.
  400. ##
  401. ## **See also:**
  402. ## * `arcsin func <#arcsin,float64>`_
  403. runnableExamples:
  404. doAssert almostEqual(sin(PI / 6), 0.5)
  405. doAssert almostEqual(sin(degToRad(90.0)), 1.0)
  406. func cos*(x: float32): float32 {.importc: "cosf", header: "<math.h>".}
  407. func cos*(x: float64): float64 {.importc: "cos", header: "<math.h>".} =
  408. ## Computes the cosine of `x`.
  409. ##
  410. ## **See also:**
  411. ## * `arccos func <#arccos,float64>`_
  412. runnableExamples:
  413. doAssert almostEqual(cos(2 * PI), 1.0)
  414. doAssert almostEqual(cos(degToRad(60.0)), 0.5)
  415. func tan*(x: float32): float32 {.importc: "tanf", header: "<math.h>".}
  416. func tan*(x: float64): float64 {.importc: "tan", header: "<math.h>".} =
  417. ## Computes the tangent of `x`.
  418. ##
  419. ## **See also:**
  420. ## * `arctan func <#arctan,float64>`_
  421. runnableExamples:
  422. doAssert almostEqual(tan(degToRad(45.0)), 1.0)
  423. doAssert almostEqual(tan(PI / 4), 1.0)
  424. func sinh*(x: float32): float32 {.importc: "sinhf", header: "<math.h>".}
  425. func sinh*(x: float64): float64 {.importc: "sinh", header: "<math.h>".} =
  426. ## Computes the [hyperbolic sine](https://en.wikipedia.org/wiki/Hyperbolic_function#Definitions) of `x`.
  427. ##
  428. ## **See also:**
  429. ## * `arcsinh func <#arcsinh,float64>`_
  430. runnableExamples:
  431. doAssert almostEqual(sinh(0.0), 0.0)
  432. doAssert almostEqual(sinh(1.0), 1.175201193643801)
  433. func cosh*(x: float32): float32 {.importc: "coshf", header: "<math.h>".}
  434. func cosh*(x: float64): float64 {.importc: "cosh", header: "<math.h>".} =
  435. ## Computes the [hyperbolic cosine](https://en.wikipedia.org/wiki/Hyperbolic_function#Definitions) of `x`.
  436. ##
  437. ## **See also:**
  438. ## * `arccosh func <#arccosh,float64>`_
  439. runnableExamples:
  440. doAssert almostEqual(cosh(0.0), 1.0)
  441. doAssert almostEqual(cosh(1.0), 1.543080634815244)
  442. func tanh*(x: float32): float32 {.importc: "tanhf", header: "<math.h>".}
  443. func tanh*(x: float64): float64 {.importc: "tanh", header: "<math.h>".} =
  444. ## Computes the [hyperbolic tangent](https://en.wikipedia.org/wiki/Hyperbolic_function#Definitions) of `x`.
  445. ##
  446. ## **See also:**
  447. ## * `arctanh func <#arctanh,float64>`_
  448. runnableExamples:
  449. doAssert almostEqual(tanh(0.0), 0.0)
  450. doAssert almostEqual(tanh(1.0), 0.7615941559557649)
  451. func arcsin*(x: float32): float32 {.importc: "asinf", header: "<math.h>".}
  452. func arcsin*(x: float64): float64 {.importc: "asin", header: "<math.h>".} =
  453. ## Computes the arc sine of `x`.
  454. ##
  455. ## **See also:**
  456. ## * `sin func <#sin,float64>`_
  457. runnableExamples:
  458. doAssert almostEqual(radToDeg(arcsin(0.0)), 0.0)
  459. doAssert almostEqual(radToDeg(arcsin(1.0)), 90.0)
  460. func arccos*(x: float32): float32 {.importc: "acosf", header: "<math.h>".}
  461. func arccos*(x: float64): float64 {.importc: "acos", header: "<math.h>".} =
  462. ## Computes the arc cosine of `x`.
  463. ##
  464. ## **See also:**
  465. ## * `cos func <#cos,float64>`_
  466. runnableExamples:
  467. doAssert almostEqual(radToDeg(arccos(0.0)), 90.0)
  468. doAssert almostEqual(radToDeg(arccos(1.0)), 0.0)
  469. func arctan*(x: float32): float32 {.importc: "atanf", header: "<math.h>".}
  470. func arctan*(x: float64): float64 {.importc: "atan", header: "<math.h>".} =
  471. ## Calculate the arc tangent of `x`.
  472. ##
  473. ## **See also:**
  474. ## * `arctan2 func <#arctan2,float64,float64>`_
  475. ## * `tan func <#tan,float64>`_
  476. runnableExamples:
  477. doAssert almostEqual(arctan(1.0), 0.7853981633974483)
  478. doAssert almostEqual(radToDeg(arctan(1.0)), 45.0)
  479. func arctan2*(y, x: float32): float32 {.importc: "atan2f", header: "<math.h>".}
  480. func arctan2*(y, x: float64): float64 {.importc: "atan2", header: "<math.h>".} =
  481. ## Calculate the arc tangent of `y/x`.
  482. ##
  483. ## It produces correct results even when the resulting angle is near
  484. ## `PI/2` or `-PI/2` (`x` near 0).
  485. ##
  486. ## **See also:**
  487. ## * `arctan func <#arctan,float64>`_
  488. runnableExamples:
  489. doAssert almostEqual(arctan2(1.0, 0.0), PI / 2.0)
  490. doAssert almostEqual(radToDeg(arctan2(1.0, 0.0)), 90.0)
  491. func arcsinh*(x: float32): float32 {.importc: "asinhf", header: "<math.h>".}
  492. func arcsinh*(x: float64): float64 {.importc: "asinh", header: "<math.h>".}
  493. ## Computes the inverse hyperbolic sine of `x`.
  494. ##
  495. ## **See also:**
  496. ## * `sinh func <#sinh,float64>`_
  497. func arccosh*(x: float32): float32 {.importc: "acoshf", header: "<math.h>".}
  498. func arccosh*(x: float64): float64 {.importc: "acosh", header: "<math.h>".}
  499. ## Computes the inverse hyperbolic cosine of `x`.
  500. ##
  501. ## **See also:**
  502. ## * `cosh func <#cosh,float64>`_
  503. func arctanh*(x: float32): float32 {.importc: "atanhf", header: "<math.h>".}
  504. func arctanh*(x: float64): float64 {.importc: "atanh", header: "<math.h>".}
  505. ## Computes the inverse hyperbolic tangent of `x`.
  506. ##
  507. ## **See also:**
  508. ## * `tanh func <#tanh,float64>`_
  509. else: # JS
  510. func log10*(x: float32): float32 {.importc: "Math.log10", nodecl.}
  511. func log10*(x: float64): float64 {.importc: "Math.log10", nodecl.}
  512. func log2*(x: float32): float32 {.importc: "Math.log2", nodecl.}
  513. func log2*(x: float64): float64 {.importc: "Math.log2", nodecl.}
  514. func exp*(x: float32): float32 {.importc: "Math.exp", nodecl.}
  515. func exp*(x: float64): float64 {.importc: "Math.exp", nodecl.}
  516. func sin*[T: float32|float64](x: T): T {.importc: "Math.sin", nodecl.}
  517. func cos*[T: float32|float64](x: T): T {.importc: "Math.cos", nodecl.}
  518. func tan*[T: float32|float64](x: T): T {.importc: "Math.tan", nodecl.}
  519. func sinh*[T: float32|float64](x: T): T {.importc: "Math.sinh", nodecl.}
  520. func cosh*[T: float32|float64](x: T): T {.importc: "Math.cosh", nodecl.}
  521. func tanh*[T: float32|float64](x: T): T {.importc: "Math.tanh", nodecl.}
  522. func arcsin*[T: float32|float64](x: T): T {.importc: "Math.asin", nodecl.}
  523. # keep this as generic or update test in `tvmops.nim` to make sure we
  524. # keep testing that generic importc procs work
  525. func arccos*[T: float32|float64](x: T): T {.importc: "Math.acos", nodecl.}
  526. func arctan*[T: float32|float64](x: T): T {.importc: "Math.atan", nodecl.}
  527. func arctan2*[T: float32|float64](y, x: T): T {.importc: "Math.atan2", nodecl.}
  528. func arcsinh*[T: float32|float64](x: T): T {.importc: "Math.asinh", nodecl.}
  529. func arccosh*[T: float32|float64](x: T): T {.importc: "Math.acosh", nodecl.}
  530. func arctanh*[T: float32|float64](x: T): T {.importc: "Math.atanh", nodecl.}
  531. func cot*[T: float32|float64](x: T): T = 1.0 / tan(x)
  532. ## Computes the cotangent of `x` (`1/tan(x)`).
  533. func sec*[T: float32|float64](x: T): T = 1.0 / cos(x)
  534. ## Computes the secant of `x` (`1/cos(x)`).
  535. func csc*[T: float32|float64](x: T): T = 1.0 / sin(x)
  536. ## Computes the cosecant of `x` (`1/sin(x)`).
  537. func coth*[T: float32|float64](x: T): T = 1.0 / tanh(x)
  538. ## Computes the hyperbolic cotangent of `x` (`1/tanh(x)`).
  539. func sech*[T: float32|float64](x: T): T = 1.0 / cosh(x)
  540. ## Computes the hyperbolic secant of `x` (`1/cosh(x)`).
  541. func csch*[T: float32|float64](x: T): T = 1.0 / sinh(x)
  542. ## Computes the hyperbolic cosecant of `x` (`1/sinh(x)`).
  543. func arccot*[T: float32|float64](x: T): T = arctan(1.0 / x)
  544. ## Computes the inverse cotangent of `x` (`arctan(1/x)`).
  545. func arcsec*[T: float32|float64](x: T): T = arccos(1.0 / x)
  546. ## Computes the inverse secant of `x` (`arccos(1/x)`).
  547. func arccsc*[T: float32|float64](x: T): T = arcsin(1.0 / x)
  548. ## Computes the inverse cosecant of `x` (`arcsin(1/x)`).
  549. func arccoth*[T: float32|float64](x: T): T = arctanh(1.0 / x)
  550. ## Computes the inverse hyperbolic cotangent of `x` (`arctanh(1/x)`).
  551. func arcsech*[T: float32|float64](x: T): T = arccosh(1.0 / x)
  552. ## Computes the inverse hyperbolic secant of `x` (`arccosh(1/x)`).
  553. func arccsch*[T: float32|float64](x: T): T = arcsinh(1.0 / x)
  554. ## Computes the inverse hyperbolic cosecant of `x` (`arcsinh(1/x)`).
  555. const windowsCC89 = defined(windows) and defined(bcc)
  556. when not defined(js): # C
  557. func hypot*(x, y: float32): float32 {.importc: "hypotf", header: "<math.h>".}
  558. func hypot*(x, y: float64): float64 {.importc: "hypot", header: "<math.h>".} =
  559. ## Computes the length of the hypotenuse of a right-angle triangle with
  560. ## `x` as its base and `y` as its height. Equivalent to `sqrt(x*x + y*y)`.
  561. runnableExamples:
  562. doAssert almostEqual(hypot(3.0, 4.0), 5.0)
  563. func pow*(x, y: float32): float32 {.importc: "powf", header: "<math.h>".}
  564. func pow*(x, y: float64): float64 {.importc: "pow", header: "<math.h>".} =
  565. ## Computes `x` raised to the power of `y`.
  566. ##
  567. ## To compute the power between integers (e.g. 2^6),
  568. ## use the `^ func <#^,T,Natural>`_.
  569. ##
  570. ## **See also:**
  571. ## * `^ func <#^,T,Natural>`_
  572. ## * `sqrt func <#sqrt,float64>`_
  573. ## * `cbrt func <#cbrt,float64>`_
  574. runnableExamples:
  575. doAssert almostEqual(pow(100, 1.5), 1000.0)
  576. doAssert almostEqual(pow(16.0, 0.5), 4.0)
  577. # TODO: add C89 version on windows
  578. when not windowsCC89:
  579. func erf*(x: float32): float32 {.importc: "erff", header: "<math.h>".}
  580. func erf*(x: float64): float64 {.importc: "erf", header: "<math.h>".}
  581. ## Computes the [error function](https://en.wikipedia.org/wiki/Error_function) for `x`.
  582. ##
  583. ## **Note:** Not available for the JS backend.
  584. func erfc*(x: float32): float32 {.importc: "erfcf", header: "<math.h>".}
  585. func erfc*(x: float64): float64 {.importc: "erfc", header: "<math.h>".}
  586. ## Computes the [complementary error function](https://en.wikipedia.org/wiki/Error_function#Complementary_error_function) for `x`.
  587. ##
  588. ## **Note:** Not available for the JS backend.
  589. func gamma*(x: float32): float32 {.importc: "tgammaf", header: "<math.h>".}
  590. func gamma*(x: float64): float64 {.importc: "tgamma", header: "<math.h>".} =
  591. ## Computes the [gamma function](https://en.wikipedia.org/wiki/Gamma_function) for `x`.
  592. ##
  593. ## **Note:** Not available for the JS backend.
  594. ##
  595. ## **See also:**
  596. ## * `lgamma func <#lgamma,float64>`_ for the natural logarithm of the gamma function
  597. runnableExamples:
  598. doAssert almostEqual(gamma(1.0), 1.0)
  599. doAssert almostEqual(gamma(4.0), 6.0)
  600. doAssert almostEqual(gamma(11.0), 3628800.0)
  601. func lgamma*(x: float32): float32 {.importc: "lgammaf", header: "<math.h>".}
  602. func lgamma*(x: float64): float64 {.importc: "lgamma", header: "<math.h>".} =
  603. ## Computes the natural logarithm of the gamma function for `x`.
  604. ##
  605. ## **Note:** Not available for the JS backend.
  606. ##
  607. ## **See also:**
  608. ## * `gamma func <#gamma,float64>`_ for gamma function
  609. func floor*(x: float32): float32 {.importc: "floorf", header: "<math.h>".}
  610. func floor*(x: float64): float64 {.importc: "floor", header: "<math.h>".} =
  611. ## Computes the floor function (i.e. the largest integer not greater than `x`).
  612. ##
  613. ## **See also:**
  614. ## * `ceil func <#ceil,float64>`_
  615. ## * `round func <#round,float64>`_
  616. ## * `trunc func <#trunc,float64>`_
  617. runnableExamples:
  618. doAssert floor(2.1) == 2.0
  619. doAssert floor(2.9) == 2.0
  620. doAssert floor(-3.5) == -4.0
  621. func ceil*(x: float32): float32 {.importc: "ceilf", header: "<math.h>".}
  622. func ceil*(x: float64): float64 {.importc: "ceil", header: "<math.h>".} =
  623. ## Computes the ceiling function (i.e. the smallest integer not smaller
  624. ## than `x`).
  625. ##
  626. ## **See also:**
  627. ## * `floor func <#floor,float64>`_
  628. ## * `round func <#round,float64>`_
  629. ## * `trunc func <#trunc,float64>`_
  630. runnableExamples:
  631. doAssert ceil(2.1) == 3.0
  632. doAssert ceil(2.9) == 3.0
  633. doAssert ceil(-2.1) == -2.0
  634. when windowsCC89:
  635. # MSVC 2010 don't have trunc/truncf
  636. # this implementation was inspired by Go-lang Math.Trunc
  637. func truncImpl(f: float64): float64 =
  638. const
  639. mask: uint64 = 0x7FF
  640. shift: uint64 = 64 - 12
  641. bias: uint64 = 0x3FF
  642. if f < 1:
  643. if f < 0: return -truncImpl(-f)
  644. elif f == 0: return f # Return -0 when f == -0
  645. else: return 0
  646. var x = cast[uint64](f)
  647. let e = (x shr shift) and mask - bias
  648. # Keep the top 12+e bits, the integer part; clear the rest.
  649. if e < 64 - 12:
  650. x = x and (not (1'u64 shl (64'u64 - 12'u64 - e) - 1'u64))
  651. result = cast[float64](x)
  652. func truncImpl(f: float32): float32 =
  653. const
  654. mask: uint32 = 0xFF
  655. shift: uint32 = 32 - 9
  656. bias: uint32 = 0x7F
  657. if f < 1:
  658. if f < 0: return -truncImpl(-f)
  659. elif f == 0: return f # Return -0 when f == -0
  660. else: return 0
  661. var x = cast[uint32](f)
  662. let e = (x shr shift) and mask - bias
  663. # Keep the top 9+e bits, the integer part; clear the rest.
  664. if e < 32 - 9:
  665. x = x and (not (1'u32 shl (32'u32 - 9'u32 - e) - 1'u32))
  666. result = cast[float32](x)
  667. func trunc*(x: float64): float64 =
  668. if classify(x) in {fcZero, fcNegZero, fcNan, fcInf, fcNegInf}: return x
  669. result = truncImpl(x)
  670. func trunc*(x: float32): float32 =
  671. if classify(x) in {fcZero, fcNegZero, fcNan, fcInf, fcNegInf}: return x
  672. result = truncImpl(x)
  673. func round*[T: float32|float64](x: T): T =
  674. ## Windows compilers prior to MSVC 2012 do not implement 'round',
  675. ## 'roundl' or 'roundf'.
  676. result = if x < 0.0: ceil(x - T(0.5)) else: floor(x + T(0.5))
  677. else:
  678. func round*(x: float32): float32 {.importc: "roundf", header: "<math.h>".}
  679. func round*(x: float64): float64 {.importc: "round", header: "<math.h>".} =
  680. ## Rounds a float to zero decimal places.
  681. ##
  682. ## Used internally by the `round func <#round,T,int>`_
  683. ## when the specified number of places is 0.
  684. ##
  685. ## **See also:**
  686. ## * `round func <#round,T,int>`_ for rounding to the specific
  687. ## number of decimal places
  688. ## * `floor func <#floor,float64>`_
  689. ## * `ceil func <#ceil,float64>`_
  690. ## * `trunc func <#trunc,float64>`_
  691. runnableExamples:
  692. doAssert round(3.4) == 3.0
  693. doAssert round(3.5) == 4.0
  694. doAssert round(4.5) == 5.0
  695. func trunc*(x: float32): float32 {.importc: "truncf", header: "<math.h>".}
  696. func trunc*(x: float64): float64 {.importc: "trunc", header: "<math.h>".} =
  697. ## Truncates `x` to the decimal point.
  698. ##
  699. ## **See also:**
  700. ## * `floor func <#floor,float64>`_
  701. ## * `ceil func <#ceil,float64>`_
  702. ## * `round func <#round,float64>`_
  703. runnableExamples:
  704. doAssert trunc(PI) == 3.0
  705. doAssert trunc(-1.85) == -1.0
  706. func `mod`*(x, y: float32): float32 {.importc: "fmodf", header: "<math.h>".}
  707. func `mod`*(x, y: float64): float64 {.importc: "fmod", header: "<math.h>".} =
  708. ## Computes the modulo operation for float values (the remainder of `x` divided by `y`).
  709. ##
  710. ## **See also:**
  711. ## * `floorMod func <#floorMod,T,T>`_ for Python-like (`%` operator) behavior
  712. runnableExamples:
  713. doAssert 6.5 mod 2.5 == 1.5
  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. else: # JS
  718. func hypot*(x, y: float32): float32 {.importc: "Math.hypot", varargs, nodecl.}
  719. func hypot*(x, y: float64): float64 {.importc: "Math.hypot", varargs, nodecl.}
  720. func pow*(x, y: float32): float32 {.importc: "Math.pow", nodecl.}
  721. func pow*(x, y: float64): float64 {.importc: "Math.pow", nodecl.}
  722. func floor*(x: float32): float32 {.importc: "Math.floor", nodecl.}
  723. func floor*(x: float64): float64 {.importc: "Math.floor", nodecl.}
  724. func ceil*(x: float32): float32 {.importc: "Math.ceil", nodecl.}
  725. func ceil*(x: float64): float64 {.importc: "Math.ceil", nodecl.}
  726. when (NimMajor, NimMinor) < (1, 5) or defined(nimLegacyJsRound):
  727. func round*(x: float): float {.importc: "Math.round", nodecl.}
  728. else:
  729. func jsRound(x: float): float {.importc: "Math.round", nodecl.}
  730. func round*[T: float64 | float32](x: T): T =
  731. if x >= 0: result = jsRound(x)
  732. else:
  733. result = ceil(x)
  734. if result - x >= T(0.5):
  735. result -= T(1.0)
  736. func trunc*(x: float32): float32 {.importc: "Math.trunc", nodecl.}
  737. func trunc*(x: float64): float64 {.importc: "Math.trunc", nodecl.}
  738. func `mod`*(x, y: float32): float32 {.importjs: "(# % #)".}
  739. func `mod`*(x, y: float64): float64 {.importjs: "(# % #)".} =
  740. ## Computes the modulo operation for float values (the remainder of `x` divided by `y`).
  741. runnableExamples:
  742. doAssert 6.5 mod 2.5 == 1.5
  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. func divmod*[T:SomeInteger](num, denom: T): (T, T) =
  747. runnableExamples:
  748. doAssert divmod(5, 2) == (2, 1)
  749. doAssert divmod(5, -3) == (-1, 2)
  750. result[0] = num div denom
  751. result[1] = num mod denom
  752. func round*[T: float32|float64](x: T, places: int): T =
  753. ## Decimal rounding on a binary floating point number.
  754. ##
  755. ## This function is NOT reliable. Floating point numbers cannot hold
  756. ## non integer decimals precisely. If `places` is 0 (or omitted),
  757. ## round to the nearest integral value following normal mathematical
  758. ## rounding rules (e.g. `round(54.5) -> 55.0`). If `places` is
  759. ## greater than 0, round to the given number of decimal places,
  760. ## e.g. `round(54.346, 2) -> 54.350000000000001421…`. If `places` is negative, round
  761. ## to the left of the decimal place, e.g. `round(537.345, -1) -> 540.0`.
  762. runnableExamples:
  763. doAssert round(PI, 2) == 3.14
  764. doAssert round(PI, 4) == 3.1416
  765. if places == 0:
  766. result = round(x)
  767. else:
  768. var mult = pow(10.0, T(places))
  769. result = round(x * mult) / mult
  770. func floorDiv*[T: SomeInteger](x, y: T): T =
  771. ## Floor division is conceptually defined as `floor(x / y)`.
  772. ##
  773. ## This is different from the `system.div <system.html#div,int,int>`_
  774. ## operator, which is defined as `trunc(x / y)`.
  775. ## That is, `div` rounds towards `0` and `floorDiv` rounds down.
  776. ##
  777. ## **See also:**
  778. ## * `system.div proc <system.html#div,int,int>`_ for integer division
  779. ## * `floorMod func <#floorMod,T,T>`_ for Python-like (`%` operator) behavior
  780. runnableExamples:
  781. doAssert floorDiv( 13, 3) == 4
  782. doAssert floorDiv(-13, 3) == -5
  783. doAssert floorDiv( 13, -3) == -5
  784. doAssert floorDiv(-13, -3) == 4
  785. result = x div y
  786. let r = x mod y
  787. if (r > 0 and y < 0) or (r < 0 and y > 0): result.dec 1
  788. func floorMod*[T: SomeNumber](x, y: T): T =
  789. ## Floor modulo is conceptually defined as `x - (floorDiv(x, y) * y)`.
  790. ##
  791. ## This func behaves the same as the `%` operator in Python.
  792. ##
  793. ## **See also:**
  794. ## * `mod func <#mod,float64,float64>`_
  795. ## * `floorDiv func <#floorDiv,T,T>`_
  796. runnableExamples:
  797. doAssert floorMod( 13, 3) == 1
  798. doAssert floorMod(-13, 3) == 2
  799. doAssert floorMod( 13, -3) == -2
  800. doAssert floorMod(-13, -3) == -1
  801. result = x mod y
  802. if (result > 0 and y < 0) or (result < 0 and y > 0): result += y
  803. func euclDiv*[T: SomeInteger](x, y: T): T {.since: (1, 5, 1).} =
  804. ## Returns euclidean division of `x` by `y`.
  805. runnableExamples:
  806. doAssert euclDiv(13, 3) == 4
  807. doAssert euclDiv(-13, 3) == -5
  808. doAssert euclDiv(13, -3) == -4
  809. doAssert euclDiv(-13, -3) == 5
  810. result = x div y
  811. if x mod y < 0:
  812. if y > 0:
  813. dec result
  814. else:
  815. inc result
  816. func euclMod*[T: SomeNumber](x, y: T): T {.since: (1, 5, 1).} =
  817. ## Returns euclidean modulo of `x` by `y`.
  818. ## `euclMod(x, y)` is non-negative.
  819. runnableExamples:
  820. doAssert euclMod(13, 3) == 1
  821. doAssert euclMod(-13, 3) == 2
  822. doAssert euclMod(13, -3) == 1
  823. doAssert euclMod(-13, -3) == 2
  824. result = x mod y
  825. if result < 0:
  826. result += abs(y)
  827. func ceilDiv*[T: SomeInteger](x, y: T): T {.inline, since: (1, 5, 1).} =
  828. ## Ceil division is conceptually defined as `ceil(x / y)`.
  829. ##
  830. ## Assumes `x >= 0` and `y > 0` (and `x + y - 1 <= high(T)` if T is SomeUnsignedInt).
  831. ##
  832. ## This is different from the `system.div <system.html#div,int,int>`_
  833. ## operator, which works like `trunc(x / y)`.
  834. ## That is, `div` rounds towards `0` and `ceilDiv` rounds up.
  835. ##
  836. ## This function has the above input limitation, because that allows the
  837. ## compiler to generate faster code and it is rarely used with
  838. ## negative values or unsigned integers close to `high(T)/2`.
  839. ## If you need a `ceilDiv` that works with any input, see:
  840. ## https://github.com/demotomohiro/divmath.
  841. ##
  842. ## **See also:**
  843. ## * `system.div proc <system.html#div,int,int>`_ for integer division
  844. ## * `floorDiv func <#floorDiv,T,T>`_ for integer division which rounds down.
  845. runnableExamples:
  846. assert ceilDiv(12, 3) == 4
  847. assert ceilDiv(13, 3) == 5
  848. when sizeof(T) == 8:
  849. type UT = uint64
  850. elif sizeof(T) == 4:
  851. type UT = uint32
  852. elif sizeof(T) == 2:
  853. type UT = uint16
  854. elif sizeof(T) == 1:
  855. type UT = uint8
  856. else:
  857. {.fatal: "Unsupported int type".}
  858. assert x >= 0 and y > 0
  859. when T is SomeUnsignedInt:
  860. assert x + y - 1 >= x
  861. # If the divisor is const, the backend C/C++ compiler generates code without a `div`
  862. # instruction, as it is slow on most CPUs.
  863. # If the divisor is a power of 2 and a const unsigned integer type, the
  864. # compiler generates faster code.
  865. # If the divisor is const and a signed integer, generated code becomes slower
  866. # than the code with unsigned integers, because division with signed integers
  867. # need to works for both positive and negative value without `idiv`/`sdiv`.
  868. # That is why this code convert parameters to unsigned.
  869. # This post contains a comparison of the performance of signed/unsigned integers:
  870. # https://github.com/nim-lang/Nim/pull/18596#issuecomment-894420984.
  871. # If signed integer arguments were not converted to unsigned integers,
  872. # `ceilDiv` wouldn't work for any positive signed integer value, because
  873. # `x + (y - 1)` can overflow.
  874. ((x.UT + (y.UT - 1.UT)) div y.UT).T
  875. func frexp*[T: float32|float64](x: T): tuple[frac: T, exp: int] {.inline.} =
  876. ## Splits `x` into a normalized fraction `frac` and an integral power of 2 `exp`,
  877. ## such that `abs(frac) in 0.5..<1` and `x == frac * 2 ^ exp`, except for special
  878. ## cases shown below.
  879. runnableExamples:
  880. doAssert frexp(8.0) == (0.5, 4)
  881. doAssert frexp(-8.0) == (-0.5, 4)
  882. doAssert frexp(0.0) == (0.0, 0)
  883. # special cases:
  884. when sizeof(int) == 8:
  885. doAssert frexp(-0.0).frac.signbit # signbit preserved for +-0
  886. doAssert frexp(Inf).frac == Inf # +- Inf preserved
  887. doAssert frexp(NaN).frac.isNaN
  888. when not defined(js):
  889. var exp: cint
  890. result.frac = c_frexp2(x, exp)
  891. result.exp = exp
  892. else:
  893. if x == 0.0:
  894. # reuse signbit implementation
  895. let uintBuffer = toBitsImpl(x)
  896. if (uintBuffer[1] shr 31) != 0:
  897. # x is -0.0
  898. result = (-0.0, 0)
  899. else:
  900. result = (0.0, 0)
  901. elif x < 0.0:
  902. result = frexp(-x)
  903. result.frac = -result.frac
  904. else:
  905. var ex = trunc(log2(x))
  906. result.exp = int(ex)
  907. result.frac = x / pow(2.0, ex)
  908. if abs(result.frac) >= 1:
  909. inc(result.exp)
  910. result.frac = result.frac / 2
  911. if result.exp == 1024 and result.frac == 0.0:
  912. result.frac = 0.99999999999999988898
  913. func frexp*[T: float32|float64](x: T, exponent: var int): T {.inline.} =
  914. ## Overload of `frexp` that calls `(result, exponent) = frexp(x)`.
  915. runnableExamples:
  916. var x: int
  917. doAssert frexp(5.0, x) == 0.625
  918. doAssert x == 3
  919. (result, exponent) = frexp(x)
  920. when not defined(js):
  921. when windowsCC89:
  922. # taken from Go-lang Math.Log2
  923. const ln2 = 0.693147180559945309417232121458176568075500134360255254120680009
  924. template log2Impl[T](x: T): T =
  925. var exp: int
  926. var frac = frexp(x, exp)
  927. # Make sure exact powers of two give an exact answer.
  928. # Don't depend on Log(0.5)*(1/Ln2)+exp being exactly exp-1.
  929. if frac == 0.5: return T(exp - 1)
  930. log10(frac) * (1 / ln2) + T(exp)
  931. func log2*(x: float32): float32 = log2Impl(x)
  932. func log2*(x: float64): float64 = log2Impl(x)
  933. ## Log2 returns the binary logarithm of x.
  934. ## The special cases are the same as for Log.
  935. else:
  936. func log2*(x: float32): float32 {.importc: "log2f", header: "<math.h>".}
  937. func log2*(x: float64): float64 {.importc: "log2", header: "<math.h>".} =
  938. ## Computes the binary logarithm (base 2) of `x`.
  939. ##
  940. ## **See also:**
  941. ## * `log func <#log,T,T>`_
  942. ## * `log10 func <#log10,float64>`_
  943. ## * `ln func <#ln,float64>`_
  944. runnableExamples:
  945. doAssert almostEqual(log2(8.0), 3.0)
  946. doAssert almostEqual(log2(1.0), 0.0)
  947. doAssert almostEqual(log2(0.0), -Inf)
  948. doAssert log2(-2.0).isNaN
  949. func splitDecimal*[T: float32|float64](x: T): tuple[intpart: T, floatpart: T] =
  950. ## Breaks `x` into an integer and a fractional part.
  951. ##
  952. ## Returns a tuple containing `intpart` and `floatpart`, representing
  953. ## the integer part and the fractional part, respectively.
  954. ##
  955. ## Both parts have the same sign as `x`. Analogous to the `modf`
  956. ## function in C.
  957. runnableExamples:
  958. doAssert splitDecimal(5.25) == (intpart: 5.0, floatpart: 0.25)
  959. doAssert splitDecimal(-2.73) == (intpart: -2.0, floatpart: -0.73)
  960. var
  961. absolute: T
  962. absolute = abs(x)
  963. result.intpart = floor(absolute)
  964. result.floatpart = absolute - result.intpart
  965. if x < 0:
  966. result.intpart = -result.intpart
  967. result.floatpart = -result.floatpart
  968. func degToRad*[T: float32|float64](d: T): T {.inline.} =
  969. ## Converts from degrees to radians.
  970. ##
  971. ## **See also:**
  972. ## * `radToDeg func <#radToDeg,T>`_
  973. runnableExamples:
  974. doAssert almostEqual(degToRad(180.0), PI)
  975. result = d * T(RadPerDeg)
  976. func radToDeg*[T: float32|float64](d: T): T {.inline.} =
  977. ## Converts from radians to degrees.
  978. ##
  979. ## **See also:**
  980. ## * `degToRad func <#degToRad,T>`_
  981. runnableExamples:
  982. doAssert almostEqual(radToDeg(2 * PI), 360.0)
  983. result = d / T(RadPerDeg)
  984. func sgn*[T: SomeNumber](x: T): int {.inline.} =
  985. ## Sign function.
  986. ##
  987. ## Returns:
  988. ## * `-1` for negative numbers and `NegInf`,
  989. ## * `1` for positive numbers and `Inf`,
  990. ## * `0` for positive zero, negative zero and `NaN`
  991. runnableExamples:
  992. doAssert sgn(5) == 1
  993. doAssert sgn(0) == 0
  994. doAssert sgn(-4.1) == -1
  995. ord(T(0) < x) - ord(x < T(0))
  996. {.pop.}
  997. {.pop.}
  998. func sum*[T](x: openArray[T]): T =
  999. ## Computes the sum of the elements in `x`.
  1000. ##
  1001. ## If `x` is empty, 0 is returned.
  1002. ##
  1003. ## **See also:**
  1004. ## * `prod func <#prod,openArray[T]>`_
  1005. ## * `cumsum func <#cumsum,openArray[T]>`_
  1006. ## * `cumsummed func <#cumsummed,openArray[T]>`_
  1007. runnableExamples:
  1008. doAssert sum([1, 2, 3, 4]) == 10
  1009. doAssert sum([-4, 3, 5]) == 4
  1010. for i in items(x): result = result + i
  1011. func prod*[T](x: openArray[T]): T =
  1012. ## Computes the product of the elements in `x`.
  1013. ##
  1014. ## If `x` is empty, 1 is returned.
  1015. ##
  1016. ## **See also:**
  1017. ## * `sum func <#sum,openArray[T]>`_
  1018. ## * `fac func <#fac,int>`_
  1019. runnableExamples:
  1020. doAssert prod([1, 2, 3, 4]) == 24
  1021. doAssert prod([-4, 3, 5]) == -60
  1022. result = T(1)
  1023. for i in items(x): result = result * i
  1024. func cumsummed*[T](x: openArray[T]): seq[T] =
  1025. ## Returns the cumulative (aka prefix) summation of `x`.
  1026. ##
  1027. ## If `x` is empty, `@[]` is returned.
  1028. ##
  1029. ## **See also:**
  1030. ## * `sum func <#sum,openArray[T]>`_
  1031. ## * `cumsum func <#cumsum,openArray[T]>`_ for the in-place version
  1032. runnableExamples:
  1033. doAssert cumsummed([1, 2, 3, 4]) == @[1, 3, 6, 10]
  1034. let xLen = x.len
  1035. if xLen == 0:
  1036. return @[]
  1037. result.setLen(xLen)
  1038. result[0] = x[0]
  1039. for i in 1 ..< xLen: result[i] = result[i - 1] + x[i]
  1040. func cumsum*[T](x: var openArray[T]) =
  1041. ## Transforms `x` in-place (must be declared as `var`) into its
  1042. ## cumulative (aka prefix) summation.
  1043. ##
  1044. ## **See also:**
  1045. ## * `sum func <#sum,openArray[T]>`_
  1046. ## * `cumsummed func <#cumsummed,openArray[T]>`_ for a version which
  1047. ## returns a cumsummed sequence
  1048. runnableExamples:
  1049. var a = [1, 2, 3, 4]
  1050. cumsum(a)
  1051. doAssert a == @[1, 3, 6, 10]
  1052. for i in 1 ..< x.len: x[i] = x[i - 1] + x[i]
  1053. func `^`*[T: SomeNumber](x: T, y: Natural): T =
  1054. ## Computes `x` to the power of `y`.
  1055. ##
  1056. ## The exponent `y` must be non-negative, use
  1057. ## `pow <#pow,float64,float64>`_ for negative exponents.
  1058. ##
  1059. ## **See also:**
  1060. ## * `pow func <#pow,float64,float64>`_ for negative exponent or
  1061. ## floats
  1062. ## * `sqrt func <#sqrt,float64>`_
  1063. ## * `cbrt func <#cbrt,float64>`_
  1064. runnableExamples:
  1065. doAssert -3 ^ 0 == 1
  1066. doAssert -3 ^ 1 == -3
  1067. doAssert -3 ^ 2 == 9
  1068. case y
  1069. of 0: result = 1
  1070. of 1: result = x
  1071. of 2: result = x * x
  1072. of 3: result = x * x * x
  1073. else:
  1074. var (x, y) = (x, y)
  1075. result = 1
  1076. while true:
  1077. if (y and 1) != 0:
  1078. result *= x
  1079. y = y shr 1
  1080. if y == 0:
  1081. break
  1082. x *= x
  1083. func gcd*[T](x, y: T): T =
  1084. ## Computes the greatest common (positive) divisor of `x` and `y`.
  1085. ##
  1086. ## Note that for floats, the result cannot always be interpreted as
  1087. ## "greatest decimal `z` such that `z*N == x and z*M == y`
  1088. ## where N and M are positive integers".
  1089. ##
  1090. ## **See also:**
  1091. ## * `gcd func <#gcd,SomeInteger,SomeInteger>`_ for an integer version
  1092. ## * `lcm func <#lcm,T,T>`_
  1093. runnableExamples:
  1094. doAssert gcd(13.5, 9.0) == 4.5
  1095. var (x, y) = (x, y)
  1096. while y != 0:
  1097. x = x mod y
  1098. swap x, y
  1099. abs x
  1100. func gcd*(x, y: SomeInteger): SomeInteger =
  1101. ## Computes the greatest common (positive) divisor of `x` and `y`,
  1102. ## using the binary GCD (aka Stein's) algorithm.
  1103. ##
  1104. ## **See also:**
  1105. ## * `gcd func <#gcd,T,T>`_ for a float version
  1106. ## * `lcm func <#lcm,T,T>`_
  1107. runnableExamples:
  1108. doAssert gcd(12, 8) == 4
  1109. doAssert gcd(17, 63) == 1
  1110. when x is SomeSignedInt:
  1111. var x = abs(x)
  1112. else:
  1113. var x = x
  1114. when y is SomeSignedInt:
  1115. var y = abs(y)
  1116. else:
  1117. var y = y
  1118. if x == 0:
  1119. return y
  1120. if y == 0:
  1121. return x
  1122. let shift = countTrailingZeroBits(x or y)
  1123. y = y shr countTrailingZeroBits(y)
  1124. while x != 0:
  1125. x = x shr countTrailingZeroBits(x)
  1126. if y > x:
  1127. swap y, x
  1128. x -= y
  1129. y shl shift
  1130. func gcd*[T](x: openArray[T]): T {.since: (1, 1).} =
  1131. ## Computes the greatest common (positive) divisor of the elements of `x`.
  1132. ##
  1133. ## **See also:**
  1134. ## * `gcd func <#gcd,T,T>`_ for a version with two arguments
  1135. runnableExamples:
  1136. doAssert gcd(@[13.5, 9.0]) == 4.5
  1137. result = x[0]
  1138. for i in 1 ..< x.len:
  1139. result = gcd(result, x[i])
  1140. func lcm*[T](x, y: T): T =
  1141. ## Computes the least common multiple of `x` and `y`.
  1142. ##
  1143. ## **See also:**
  1144. ## * `gcd func <#gcd,T,T>`_
  1145. runnableExamples:
  1146. doAssert lcm(24, 30) == 120
  1147. doAssert lcm(13, 39) == 39
  1148. x div gcd(x, y) * y
  1149. func clamp*[T](val: T, bounds: Slice[T]): T {.since: (1, 5), inline.} =
  1150. ## Like `system.clamp`, but takes a slice, so you can easily clamp within a range.
  1151. runnableExamples:
  1152. assert clamp(10, 1 .. 5) == 5
  1153. assert clamp(1, 1 .. 3) == 1
  1154. type A = enum a0, a1, a2, a3, a4, a5
  1155. assert a1.clamp(a2..a4) == a2
  1156. assert clamp((3, 0), (1, 0) .. (2, 9)) == (2, 9)
  1157. doAssertRaises(AssertionDefect): discard clamp(1, 3..2) # invalid bounds
  1158. assert bounds.a <= bounds.b, $(bounds.a, bounds.b)
  1159. clamp(val, bounds.a, bounds.b)
  1160. func lcm*[T](x: openArray[T]): T {.since: (1, 1).} =
  1161. ## Computes the least common multiple of the elements of `x`.
  1162. ##
  1163. ## **See also:**
  1164. ## * `lcm func <#lcm,T,T>`_ for a version with two arguments
  1165. runnableExamples:
  1166. doAssert lcm(@[24, 30]) == 120
  1167. result = x[0]
  1168. for i in 1 ..< x.len:
  1169. result = lcm(result, x[i])