math.nim 43 KB

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