math.nim 45 KB

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