math.nim 45 KB

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