math.nim 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  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. import system/countbits_impl
  54. when defined(nimPreviewSlimSystem):
  55. import std/assertions
  56. when not defined(js) and not defined(nimscript): # C
  57. proc c_isnan(x: float): bool {.importc: "isnan", header: "<math.h>".}
  58. # a generic like `x: SomeFloat` might work too if this is implemented via a C macro.
  59. proc c_copysign(x, y: cfloat): cfloat {.importc: "copysignf", header: "<math.h>".}
  60. proc c_copysign(x, y: cdouble): cdouble {.importc: "copysign", header: "<math.h>".}
  61. proc c_signbit(x: SomeFloat): cint {.importc: "signbit", header: "<math.h>".}
  62. # don't export `c_frexp` in the future and remove `c_frexp2`.
  63. func c_frexp2(x: cfloat, exponent: var cint): cfloat {.
  64. importc: "frexpf", header: "<math.h>".}
  65. func c_frexp2(x: cdouble, exponent: var cint): cdouble {.
  66. importc: "frexp", header: "<math.h>".}
  67. type
  68. div_t {.importc, header: "<stdlib.h>".} = object
  69. quot: cint
  70. rem: cint
  71. ldiv_t {.importc, header: "<stdlib.h>".} = object
  72. quot: clong
  73. rem: clong
  74. lldiv_t {.importc, header: "<stdlib.h>".} = object
  75. quot: clonglong
  76. rem: clonglong
  77. when cint isnot clong:
  78. func divmod_c(x, y: cint): div_t {.importc: "div", header: "<stdlib.h>".}
  79. when clong isnot clonglong:
  80. func divmod_c(x, y: clonglong): lldiv_t {.importc: "lldiv", header: "<stdlib.h>".}
  81. func divmod_c(x, y: clong): ldiv_t {.importc: "ldiv", header: "<stdlib.h>".}
  82. func divmod*[T: SomeInteger](x, y: T): (T, T) {.inline.} =
  83. ## Specialized instructions for computing both division and modulus.
  84. ## Return structure is: (quotient, remainder)
  85. runnableExamples:
  86. doAssert divmod(5, 2) == (2, 1)
  87. doAssert divmod(5, -3) == (-1, 2)
  88. when T is cint | clong | clonglong:
  89. when compileOption("overflowChecks"):
  90. if y == 0:
  91. raise new(DivByZeroDefect)
  92. elif (x == T.low and y == -1.T):
  93. raise new(OverflowDefect)
  94. let res = divmod_c(x, y)
  95. result[0] = res.quot
  96. result[1] = res.rem
  97. else:
  98. result[0] = x div y
  99. result[1] = x mod y
  100. func binom*(n, k: int): int =
  101. ## Computes the [binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient).
  102. runnableExamples:
  103. doAssert binom(6, 2) == 15
  104. doAssert binom(-6, 2) == 1
  105. doAssert binom(6, 0) == 1
  106. if k <= 0: return 1
  107. if 2 * k > n: return binom(n, n - k)
  108. result = n
  109. for i in countup(2, k):
  110. result = (result * (n + 1 - i)) div i
  111. func createFactTable[N: static[int]]: array[N, int] =
  112. result[0] = 1
  113. for i in 1 ..< N:
  114. result[i] = result[i - 1] * i
  115. func fac*(n: int): int =
  116. ## Computes the [factorial](https://en.wikipedia.org/wiki/Factorial) of
  117. ## a non-negative integer `n`.
  118. ##
  119. ## **See also:**
  120. ## * `prod func <#prod,openArray[T]>`_
  121. runnableExamples:
  122. doAssert fac(0) == 1
  123. doAssert fac(4) == 24
  124. doAssert fac(10) == 3628800
  125. const factTable =
  126. when sizeof(int) == 2:
  127. createFactTable[5]()
  128. elif sizeof(int) == 4:
  129. createFactTable[13]()
  130. else:
  131. createFactTable[21]()
  132. assert(n >= 0, $n & " must not be negative.")
  133. assert(n < factTable.len, $n & " is too large to look up in the table")
  134. factTable[n]
  135. {.push checks: off, line_dir: off, stack_trace: off.}
  136. when defined(posix) and not defined(genode) and not defined(macosx):
  137. {.passl: "-lm".}
  138. const
  139. PI* = 3.1415926535897932384626433 ## The circle constant PI (Ludolph's number).
  140. TAU* = 2.0 * PI ## The circle constant TAU (= 2 * PI).
  141. E* = 2.71828182845904523536028747 ## Euler's number.
  142. MaxFloat64Precision* = 16 ## Maximum number of meaningful digits
  143. ## after the decimal point for Nim's
  144. ## `float64` type.
  145. MaxFloat32Precision* = 8 ## Maximum number of meaningful digits
  146. ## after the decimal point for Nim's
  147. ## `float32` type.
  148. MaxFloatPrecision* = MaxFloat64Precision ## Maximum number of
  149. ## meaningful digits
  150. ## after the decimal point
  151. ## for Nim's `float` type.
  152. MinFloatNormal* = 2.225073858507201e-308 ## Smallest normal number for Nim's
  153. ## `float` type (= 2^-1022).
  154. RadPerDeg = PI / 180.0 ## Number of radians per degree.
  155. type
  156. FloatClass* = enum ## Describes the class a floating point value belongs to.
  157. ## This is the type that is returned by the
  158. ## `classify func <#classify,float>`_.
  159. fcNormal, ## value is an ordinary nonzero floating point value
  160. fcSubnormal, ## value is a subnormal (a very small) floating point value
  161. fcZero, ## value is zero
  162. fcNegZero, ## value is the negative zero
  163. fcNan, ## value is Not a Number (NaN)
  164. fcInf, ## value is positive infinity
  165. fcNegInf ## value is negative infinity
  166. func isNaN*(x: SomeFloat): bool {.inline, since: (1,5,1).} =
  167. ## Returns whether `x` is a `NaN`, more efficiently than via `classify(x) == fcNan`.
  168. ## Works even with `--passc:-ffast-math`.
  169. runnableExamples:
  170. doAssert NaN.isNaN
  171. doAssert not Inf.isNaN
  172. doAssert not isNaN(3.1415926)
  173. template fn: untyped = result = x != x
  174. when nimvm: fn()
  175. else:
  176. when defined(js) or defined(nimscript): fn()
  177. else: result = c_isnan(x)
  178. when defined(js):
  179. import std/private/jsutils
  180. proc toBitsImpl(x: float): array[2, uint32] =
  181. let buffer = newArrayBuffer(8)
  182. let a = newFloat64Array(buffer)
  183. let b = newUint32Array(buffer)
  184. a[0] = x
  185. {.emit: "`result` = `b`;".}
  186. # result = cast[array[2, uint32]](b)
  187. proc jsSetSign(x: float, sgn: bool): float =
  188. let buffer = newArrayBuffer(8)
  189. let a = newFloat64Array(buffer)
  190. let b = newUint32Array(buffer)
  191. a[0] = x
  192. {.emit: """
  193. function updateBit(num, bitPos, bitVal) {
  194. return (num & ~(1 << bitPos)) | (bitVal << bitPos);
  195. }
  196. `b`[1] = updateBit(`b`[1], 31, `sgn`);
  197. `result` = `a`[0];
  198. """.}
  199. proc signbit*(x: SomeFloat): bool {.inline, since: (1, 5, 1).} =
  200. ## Returns true if `x` is negative, false otherwise.
  201. runnableExamples:
  202. doAssert not signbit(0.0)
  203. doAssert signbit(-0.0)
  204. doAssert signbit(-0.1)
  205. doAssert not signbit(0.1)
  206. when defined(js):
  207. let uintBuffer = toBitsImpl(x)
  208. result = (uintBuffer[1] shr 31) != 0
  209. else:
  210. result = c_signbit(x) != 0
  211. func copySign*[T: SomeFloat](x, y: T): T {.inline, since: (1, 5, 1).} =
  212. ## Returns a value with the magnitude of `x` and the sign of `y`;
  213. ## this works even if x or y are NaN, infinity or zero, all of which can carry a sign.
  214. runnableExamples:
  215. doAssert copySign(10.0, 1.0) == 10.0
  216. doAssert copySign(10.0, -1.0) == -10.0
  217. doAssert copySign(-Inf, -0.0) == -Inf
  218. doAssert copySign(NaN, 1.0).isNaN
  219. doAssert copySign(1.0, copySign(NaN, -1.0)) == -1.0
  220. # TODO: use signbit for examples
  221. when defined(js):
  222. let uintBuffer = toBitsImpl(y)
  223. let sgn = (uintBuffer[1] shr 31) != 0
  224. result = jsSetSign(x, sgn)
  225. else:
  226. when nimvm: # not exact but we have a vmops for recent enough nim
  227. if y > 0.0 or (y == 0.0 and 1.0 / y > 0.0):
  228. result = abs(x)
  229. elif y <= 0.0:
  230. result = -abs(x)
  231. else: # must be NaN
  232. result = abs(x)
  233. else: result = c_copysign(x, y)
  234. func classify*(x: float): FloatClass =
  235. ## Classifies a floating point value.
  236. ##
  237. ## Returns `x`'s class as specified by the `FloatClass enum<#FloatClass>`_.
  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 isNan(x): return fcNan
  246. if x == 0.0:
  247. if 1.0 / x == Inf:
  248. return fcZero
  249. else:
  250. return fcNegZero
  251. if x * 0.5 == x:
  252. if x > 0.0: return fcInf
  253. else: return fcNegInf
  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. ## You may use the `^ func <#^, T, U>`_ instead.
  569. ##
  570. ## **See also:**
  571. ## * `^ (SomeNumber, Natural) func <#^,T,Natural>`_
  572. ## * `^ (SomeNumber, SomeFloat) func <#^,T,U>`_
  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. ## * `^ func <#^,T,U>`_ for negative exponent or floats
  1062. ## * `pow func <#pow,float64,float64>`_ for `float32` or `float64` output
  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 isInteger(y: SomeFloat): bool =
  1085. ## Determines if a float represents an integer
  1086. return round(y) == y
  1087. func `^`*[T: SomeNumber, U: SomeFloat](x: T, y: U): float =
  1088. ## Computes `x` to the power of `y`.
  1089. ##
  1090. ## Error handling follows the C++ specification even for the JS backend
  1091. ## https://en.cppreference.com/w/cpp/numeric/math/pow
  1092. ##
  1093. ## **See also:**
  1094. ## * `^ func <#^,T,Natural>`_
  1095. ## * `pow func <#pow,float64,float64>`_ for `float32` or `float64` output
  1096. ## * `sqrt func <#sqrt,float64>`_
  1097. ## * `cbrt func <#cbrt,float64>`_
  1098. runnableExamples:
  1099. doAssert almostEqual(5.5 ^ 2.2, 42.540042248725975)
  1100. doAssert 1.0 ^ Inf == 1.0
  1101. let
  1102. isZero_x: bool = (x == 0.0 or x == -0.0)
  1103. isNegZero: bool = classify(x) == fcNegZero
  1104. isPosZero: bool = classify(x) == fcZero
  1105. yIsFinite: bool = (y != Inf and y != -Inf)
  1106. yIsOddInteger: bool = (isInteger(y) and yIsFinite and (abs(int(y) mod 2) == 1))
  1107. assert not(isPosZero and y < 0 and yIsOddInteger)
  1108. assert not(isNegZero and y < 0 and yIsOddInteger)
  1109. assert not(isZero_x and y < 0 and y != -Inf)
  1110. assert not(isZero_x and y == -Inf)
  1111. assert not(x < 0 and not isInteger(x) and yIsFinite and not yIsOddInteger)
  1112. when defined(js):
  1113. # JS behavior follows an old version of IEEE 754 for compatibility reasons
  1114. # See https://262.ecma-international.org/#sec-numeric-types-number-exponentiate
  1115. if (x == 1.0 or x == -1.0) and not yIsFinite:
  1116. float(1.0)
  1117. elif x == 1.0 and y.isNan():
  1118. float(1.0)
  1119. else:
  1120. float(pow(x, y))
  1121. else:
  1122. float(pow(x, y))
  1123. func gcd*[T](x, y: T): T =
  1124. ## Computes the greatest common (positive) divisor of `x` and `y`.
  1125. ##
  1126. ## Note that for floats, the result cannot always be interpreted as
  1127. ## "greatest decimal `z` such that `z*N == x and z*M == y`
  1128. ## where N and M are positive integers".
  1129. ##
  1130. ## **See also:**
  1131. ## * `gcd func <#gcd,SomeInteger,SomeInteger>`_ for an integer version
  1132. ## * `lcm func <#lcm,T,T>`_
  1133. runnableExamples:
  1134. doAssert gcd(13.5, 9.0) == 4.5
  1135. var (x, y) = (x, y)
  1136. while y != 0:
  1137. x = x mod y
  1138. swap x, y
  1139. abs x
  1140. when useBuiltins:
  1141. ## this func uses bitwise comparisons from C compilers, which are not always available.
  1142. func gcd*(x, y: SomeInteger): SomeInteger =
  1143. ## Computes the greatest common (positive) divisor of `x` and `y`,
  1144. ## using the binary GCD (aka Stein's) algorithm.
  1145. ##
  1146. ## **See also:**
  1147. ## * `gcd func <#gcd,T,T>`_ for a float version
  1148. ## * `lcm func <#lcm,T,T>`_
  1149. runnableExamples:
  1150. doAssert gcd(12, 8) == 4
  1151. doAssert gcd(17, 63) == 1
  1152. when x is SomeSignedInt:
  1153. var x = abs(x)
  1154. else:
  1155. var x = x
  1156. when y is SomeSignedInt:
  1157. var y = abs(y)
  1158. else:
  1159. var y = y
  1160. if x == 0:
  1161. return y
  1162. if y == 0:
  1163. return x
  1164. let shift = countTrailingZeroBits(x or y)
  1165. y = y shr countTrailingZeroBits(y)
  1166. while x != 0:
  1167. x = x shr countTrailingZeroBits(x)
  1168. if y > x:
  1169. swap y, x
  1170. x -= y
  1171. y shl shift
  1172. func gcd*[T](x: openArray[T]): T {.since: (1, 1).} =
  1173. ## Computes the greatest common (positive) divisor of the elements of `x`.
  1174. ##
  1175. ## **See also:**
  1176. ## * `gcd func <#gcd,T,T>`_ for a version with two arguments
  1177. runnableExamples:
  1178. doAssert gcd(@[13.5, 9.0]) == 4.5
  1179. result = x[0]
  1180. for i in 1 ..< x.len:
  1181. result = gcd(result, x[i])
  1182. func lcm*[T](x, y: T): T =
  1183. ## Computes the least common multiple of `x` and `y`.
  1184. ##
  1185. ## **See also:**
  1186. ## * `gcd func <#gcd,T,T>`_
  1187. runnableExamples:
  1188. doAssert lcm(24, 30) == 120
  1189. doAssert lcm(13, 39) == 39
  1190. x div gcd(x, y) * y
  1191. func clamp*[T](val: T, bounds: Slice[T]): T {.since: (1, 5), inline.} =
  1192. ## Like `system.clamp`, but takes a slice, so you can easily clamp within a range.
  1193. runnableExamples:
  1194. assert clamp(10, 1 .. 5) == 5
  1195. assert clamp(1, 1 .. 3) == 1
  1196. type A = enum a0, a1, a2, a3, a4, a5
  1197. assert a1.clamp(a2..a4) == a2
  1198. assert clamp((3, 0), (1, 0) .. (2, 9)) == (2, 9)
  1199. doAssertRaises(AssertionDefect): discard clamp(1, 3..2) # invalid bounds
  1200. assert bounds.a <= bounds.b, $(bounds.a, bounds.b)
  1201. clamp(val, bounds.a, bounds.b)
  1202. func lcm*[T](x: openArray[T]): T {.since: (1, 1).} =
  1203. ## Computes the least common multiple of the elements of `x`.
  1204. ##
  1205. ## **See also:**
  1206. ## * `lcm func <#lcm,T,T>`_ for a version with two arguments
  1207. runnableExamples:
  1208. doAssert lcm(@[24, 30]) == 120
  1209. result = x[0]
  1210. for i in 1 ..< x.len:
  1211. result = lcm(result, x[i])