math.nim 45 KB

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