math.nim 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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. ## This module is available for the `JavaScript target
  13. ## <backends.html#the-javascript-target>`_.
  14. ##
  15. ## Note that the trigonometric functions naturally operate on radians.
  16. ## The helper functions `degToRad` and `radToDeg` provide conversion
  17. ## between radians and degrees.
  18. include "system/inclrtl"
  19. {.push debugger:off .} # the user does not want to trace a part
  20. # of the standard library!
  21. import bitops
  22. proc binom*(n, k: int): int {.noSideEffect.} =
  23. ## Computes the `binomial coefficient <https://en.wikipedia.org/wiki/Binomial_coefficient>`_.
  24. ##
  25. ## .. code-block:: nim
  26. ## echo binom(6, 2) ## 15
  27. if k <= 0: return 1
  28. if 2*k > n: return binom(n, n-k)
  29. result = n
  30. for i in countup(2, k):
  31. result = (result * (n + 1 - i)) div i
  32. proc createFactTable[N: static[int]]: array[N, int] =
  33. result[0] = 1
  34. for i in 1 ..< N:
  35. result[i] = result[i - 1] * i
  36. proc fac*(n: int): int =
  37. ## Computes the `factorial <https://en.wikipedia.org/wiki/Factorial>`_ of a non-negative integer ``n``
  38. ##
  39. ## .. code-block:: nim
  40. ## echo fac(4) ## 24
  41. const factTable =
  42. when sizeof(int) == 4:
  43. createFactTable[13]()
  44. else:
  45. createFactTable[21]()
  46. assert(n >= 0, $n & " must not be negative.")
  47. assert(n < factTable.len, $n & " is too large to look up in the table")
  48. factTable[n]
  49. {.push checks:off, line_dir:off, stack_trace:off.}
  50. when defined(Posix):
  51. {.passl: "-lm".}
  52. const
  53. PI* = 3.1415926535897932384626433 ## the circle constant PI (Ludolph's number)
  54. TAU* = 2.0 * PI ## the circle constant TAU (= 2 * PI)
  55. E* = 2.71828182845904523536028747 ## Euler's number
  56. MaxFloat64Precision* = 16 ## maximum number of meaningful digits
  57. ## after the decimal point for Nim's
  58. ## ``float64`` type.
  59. MaxFloat32Precision* = 8 ## maximum number of meaningful digits
  60. ## after the decimal point for Nim's
  61. ## ``float32`` type.
  62. MaxFloatPrecision* = MaxFloat64Precision ## maximum number of
  63. ## meaningful digits
  64. ## after the decimal point
  65. ## for Nim's ``float`` type.
  66. RadPerDeg = PI / 180.0 ## number of radians per degree
  67. type
  68. FloatClass* = enum ## describes the class a floating point value belongs to.
  69. ## This is the type that is returned by `classify`.
  70. fcNormal, ## value is an ordinary nonzero floating point value
  71. fcSubnormal, ## value is a subnormal (a very small) floating point value
  72. fcZero, ## value is zero
  73. fcNegZero, ## value is the negative zero
  74. fcNan, ## value is Not-A-Number (NAN)
  75. fcInf, ## value is positive infinity
  76. fcNegInf ## value is negative infinity
  77. proc classify*(x: float): FloatClass =
  78. ## Classifies a floating point value. Returns ``x``'s class as specified by
  79. ## `FloatClass`.
  80. ##
  81. ## .. code-block:: nim
  82. ## echo classify(0.3) ## fcNormal
  83. ## echo classify(0.0) ## fcZero
  84. ## echo classify(0.3/0.0) ## fcInf
  85. # JavaScript and most C compilers have no classify:
  86. if x == 0.0:
  87. if 1.0/x == Inf:
  88. return fcZero
  89. else:
  90. return fcNegZero
  91. if x*0.5 == x:
  92. if x > 0.0: return fcInf
  93. else: return fcNegInf
  94. if x != x: return fcNan
  95. return fcNormal
  96. # XXX: fcSubnormal is not detected!
  97. proc isPowerOfTwo*(x: int): bool {.noSideEffect.} =
  98. ## Returns ``true``, if ``x`` is a power of two, ``false`` otherwise.
  99. ## Zero and negative numbers are not a power of two.
  100. ##
  101. ## .. code-block:: nim
  102. ## echo isPowerOfTwo(5) ## false
  103. ## echo isPowerOfTwo(8) ## true
  104. return (x > 0) and ((x and (x - 1)) == 0)
  105. proc nextPowerOfTwo*(x: int): int {.noSideEffect.} =
  106. ## Returns ``x`` rounded up to the nearest power of two.
  107. ## Zero and negative numbers get rounded up to 1.
  108. ##
  109. ## .. code-block:: nim
  110. ## echo nextPowerOfTwo(8) ## 8
  111. ## echo nextPowerOfTwo(9) ## 16
  112. result = x - 1
  113. when defined(cpu64):
  114. result = result or (result shr 32)
  115. when sizeof(int) > 2:
  116. result = result or (result shr 16)
  117. when sizeof(int) > 1:
  118. result = result or (result shr 8)
  119. result = result or (result shr 4)
  120. result = result or (result shr 2)
  121. result = result or (result shr 1)
  122. result += 1 + ord(x<=0)
  123. proc countBits32*(n: int32): int {.noSideEffect.} =
  124. ## Counts the set bits in ``n``.
  125. ##
  126. ## .. code-block:: nim
  127. ## echo countBits32(13'i32) ## 3
  128. var v = n
  129. v = v -% ((v shr 1'i32) and 0x55555555'i32)
  130. v = (v and 0x33333333'i32) +% ((v shr 2'i32) and 0x33333333'i32)
  131. result = ((v +% (v shr 4'i32) and 0xF0F0F0F'i32) *% 0x1010101'i32) shr 24'i32
  132. proc sum*[T](x: openArray[T]): T {.noSideEffect.} =
  133. ## Computes the sum of the elements in ``x``.
  134. ## If ``x`` is empty, 0 is returned.
  135. ##
  136. ## .. code-block:: nim
  137. ## echo sum([1.0, 2.5, -3.0, 4.3]) ## 4.8
  138. for i in items(x): result = result + i
  139. proc prod*[T](x: openArray[T]): T {.noSideEffect.} =
  140. ## Computes the product of the elements in ``x``.
  141. ## If ``x`` is empty, 1 is returned.
  142. ##
  143. ## .. code-block:: nim
  144. ## echo prod([1.0, 3.0, -0.2]) ## -0.6
  145. result = 1.T
  146. for i in items(x): result = result * i
  147. {.push noSideEffect.}
  148. when not defined(JS): # C
  149. proc sqrt*(x: float32): float32 {.importc: "sqrtf", header: "<math.h>".}
  150. proc sqrt*(x: float64): float64 {.importc: "sqrt", header: "<math.h>".}
  151. ## Computes the square root of ``x``.
  152. ##
  153. ## .. code-block:: nim
  154. ## echo sqrt(1.44) ## 1.2
  155. proc cbrt*(x: float32): float32 {.importc: "cbrtf", header: "<math.h>".}
  156. proc cbrt*(x: float64): float64 {.importc: "cbrt", header: "<math.h>".}
  157. ## Computes the cubic root of ``x``.
  158. ##
  159. ## .. code-block:: nim
  160. ## echo cbrt(2.197) ## 1.3
  161. proc ln*(x: float32): float32 {.importc: "logf", header: "<math.h>".}
  162. proc ln*(x: float64): float64 {.importc: "log", header: "<math.h>".}
  163. ## Computes the `natural logarithm <https://en.wikipedia.org/wiki/Natural_logarithm>`_ of ``x``.
  164. ##
  165. ## .. code-block:: nim
  166. ## echo ln(exp(4.0)) ## 4.0
  167. else: # JS
  168. proc sqrt*(x: float32): float32 {.importc: "Math.sqrt", nodecl.}
  169. proc sqrt*(x: float64): float64 {.importc: "Math.sqrt", nodecl.}
  170. proc ln*(x: float32): float32 {.importc: "Math.log", nodecl.}
  171. proc ln*(x: float64): float64 {.importc: "Math.log", nodecl.}
  172. proc log*[T: SomeFloat](x, base: T): T =
  173. ## Computes the logarithm of ``x`` to base ``base``.
  174. ##
  175. ## .. code-block:: nim
  176. ## echo log(9.0, 3.0) ## 2.0
  177. ln(x) / ln(base)
  178. when not defined(JS): # C
  179. proc log10*(x: float32): float32 {.importc: "log10f", header: "<math.h>".}
  180. proc log10*(x: float64): float64 {.importc: "log10", header: "<math.h>".}
  181. ## Computes the common logarithm (base 10) of ``x``.
  182. ##
  183. ## .. code-block:: nim
  184. ## echo log10(100.0) ## 2.0
  185. proc exp*(x: float32): float32 {.importc: "expf", header: "<math.h>".}
  186. proc exp*(x: float64): float64 {.importc: "exp", header: "<math.h>".}
  187. ## Computes the exponential function of ``x`` (pow(E, x)).
  188. ##
  189. ## .. code-block:: nim
  190. ## echo exp(1.0) ## 2.718281828459045
  191. ## echo ln(exp(4.0)) ## 4.0
  192. proc sin*(x: float32): float32 {.importc: "sinf", header: "<math.h>".}
  193. proc sin*(x: float64): float64 {.importc: "sin", header: "<math.h>".}
  194. ## Computes the sine of ``x``.
  195. ##
  196. ## .. code-block:: nim
  197. ## echo sin(PI / 6) ## 0.4999999999999999
  198. ## echo sin(degToRad(90.0)) ## 1.0
  199. proc cos*(x: float32): float32 {.importc: "cosf", header: "<math.h>".}
  200. proc cos*(x: float64): float64 {.importc: "cos", header: "<math.h>".}
  201. ## Computes the cosine of ``x``.
  202. ##
  203. ## .. code-block:: nim
  204. ## echo cos(2 * PI) ## 1.0
  205. ## echo cos(degToRad(60.0)) ## 0.5000000000000001
  206. proc tan*(x: float32): float32 {.importc: "tanf", header: "<math.h>".}
  207. proc tan*(x: float64): float64 {.importc: "tan", header: "<math.h>".}
  208. ## Computes the tangent of ``x``.
  209. ##
  210. ## .. code-block:: nim
  211. ## echo tan(degToRad(45.0)) ## 0.9999999999999999
  212. ## echo tan(PI / 4) ## 0.9999999999999999
  213. proc sinh*(x: float32): float32 {.importc: "sinhf", header: "<math.h>".}
  214. proc sinh*(x: float64): float64 {.importc: "sinh", header: "<math.h>".}
  215. ## Computes the `hyperbolic sine <https://en.wikipedia.org/wiki/Hyperbolic_function#Definitions>`_ of ``x``.
  216. ##
  217. ## .. code-block:: nim
  218. ## echo sinh(1.0) ## 1.175201193643801
  219. proc cosh*(x: float32): float32 {.importc: "coshf", header: "<math.h>".}
  220. proc cosh*(x: float64): float64 {.importc: "cosh", header: "<math.h>".}
  221. ## Computes the `hyperbolic cosine <https://en.wikipedia.org/wiki/Hyperbolic_function#Definitions>`_ of ``x``.
  222. ##
  223. ## .. code-block:: nim
  224. ## echo cosh(1.0) ## 1.543080634815244
  225. proc tanh*(x: float32): float32 {.importc: "tanhf", header: "<math.h>".}
  226. proc tanh*(x: float64): float64 {.importc: "tanh", header: "<math.h>".}
  227. ## Computes the `hyperbolic tangent <https://en.wikipedia.org/wiki/Hyperbolic_function#Definitions>`_ of ``x``.
  228. ##
  229. ## .. code-block:: nim
  230. ## echo tanh(1.0) ## 0.7615941559557649
  231. proc arccos*(x: float32): float32 {.importc: "acosf", header: "<math.h>".}
  232. proc arccos*(x: float64): float64 {.importc: "acos", header: "<math.h>".}
  233. ## Computes the arc cosine of ``x``.
  234. ##
  235. ## .. code-block:: nim
  236. ## echo arccos(1.0) ## 0.0
  237. proc arcsin*(x: float32): float32 {.importc: "asinf", header: "<math.h>".}
  238. proc arcsin*(x: float64): float64 {.importc: "asin", header: "<math.h>".}
  239. ## Computes the arc sine of ``x``.
  240. proc arctan*(x: float32): float32 {.importc: "atanf", header: "<math.h>".}
  241. proc arctan*(x: float64): float64 {.importc: "atan", header: "<math.h>".}
  242. ## Calculate the arc tangent of ``x``.
  243. ##
  244. ## .. code-block:: nim
  245. ## echo arctan(1.0) ## 0.7853981633974483
  246. ## echo radToDeg(arctan(1.0)) ## 45.0
  247. proc arctan2*(y, x: float32): float32 {.importc: "atan2f", header: "<math.h>".}
  248. proc arctan2*(y, x: float64): float64 {.importc: "atan2", header: "<math.h>".}
  249. ## Calculate the arc tangent of ``y`` / ``x``.
  250. ## `arctan2` returns the arc tangent of ``y`` / ``x``; it produces correct
  251. ## results even when the resulting angle is near pi/2 or -pi/2
  252. ## (``x`` near 0).
  253. ##
  254. ## .. code-block:: nim
  255. ## echo arctan2(1.0, 0.0) ## 1.570796326794897
  256. ## echo radToDeg(arctan2(1.0, 0.0)) ## 90.0
  257. proc arcsinh*(x: float32): float32 {.importc: "asinhf", header: "<math.h>".}
  258. proc arcsinh*(x: float64): float64 {.importc: "asinh", header: "<math.h>".}
  259. ## Computes the inverse hyperbolic sine of ``x``.
  260. proc arccosh*(x: float32): float32 {.importc: "acoshf", header: "<math.h>".}
  261. proc arccosh*(x: float64): float64 {.importc: "acosh", header: "<math.h>".}
  262. ## Computes the inverse hyperbolic cosine of ``x``.
  263. proc arctanh*(x: float32): float32 {.importc: "atanhf", header: "<math.h>".}
  264. proc arctanh*(x: float64): float64 {.importc: "atanh", header: "<math.h>".}
  265. ## Computes the inverse hyperbolic tangent of ``x``.
  266. else: # JS
  267. proc log10*(x: float32): float32 {.importc: "Math.log10", nodecl.}
  268. proc log10*(x: float64): float64 {.importc: "Math.log10", nodecl.}
  269. proc log2*(x: float32): float32 {.importc: "Math.log2", nodecl.}
  270. proc log2*(x: float64): float64 {.importc: "Math.log2", nodecl.}
  271. proc exp*(x: float32): float32 {.importc: "Math.exp", nodecl.}
  272. proc exp*(x: float64): float64 {.importc: "Math.exp", nodecl.}
  273. proc sin*[T: float32|float64](x: T): T {.importc: "Math.sin", nodecl.}
  274. proc cos*[T: float32|float64](x: T): T {.importc: "Math.cos", nodecl.}
  275. proc tan*[T: float32|float64](x: T): T {.importc: "Math.tan", nodecl.}
  276. proc sinh*[T: float32|float64](x: T): T {.importc: "Math.sinh", nodecl.}
  277. proc cosh*[T: float32|float64](x: T): T {.importc: "Math.cosh", nodecl.}
  278. proc tanh*[T: float32|float64](x: T): T {.importc: "Math.tanh", nodecl.}
  279. proc arcsin*[T: float32|float64](x: T): T {.importc: "Math.asin", nodecl.}
  280. proc arccos*[T: float32|float64](x: T): T {.importc: "Math.acos", nodecl.}
  281. proc arctan*[T: float32|float64](x: T): T {.importc: "Math.atan", nodecl.}
  282. proc arctan2*[T: float32|float64](y, x: T): T {.importC: "Math.atan2", nodecl.}
  283. proc arcsinh*[T: float32|float64](x: T): T {.importc: "Math.asinh", nodecl.}
  284. proc arccosh*[T: float32|float64](x: T): T {.importc: "Math.acosh", nodecl.}
  285. proc arctanh*[T: float32|float64](x: T): T {.importc: "Math.atanh", nodecl.}
  286. proc cot*[T: float32|float64](x: T): T = 1.0 / tan(x)
  287. ## Computes the cotangent of ``x``.
  288. proc sec*[T: float32|float64](x: T): T = 1.0 / cos(x)
  289. ## Computes the secant of ``x``.
  290. proc csc*[T: float32|float64](x: T): T = 1.0 / sin(x)
  291. ## Computes the cosecant of ``x``.
  292. proc coth*[T: float32|float64](x: T): T = 1.0 / tanh(x)
  293. ## Computes the hyperbolic cotangent of ``x``.
  294. proc sech*[T: float32|float64](x: T): T = 1.0 / cosh(x)
  295. ## Computes the hyperbolic secant of ``x``.
  296. proc csch*[T: float32|float64](x: T): T = 1.0 / sinh(x)
  297. ## Computes the hyperbolic cosecant of ``x``.
  298. proc arccot*[T: float32|float64](x: T): T = arctan(1.0 / x)
  299. ## Computes the inverse cotangent of ``x``.
  300. proc arcsec*[T: float32|float64](x: T): T = arccos(1.0 / x)
  301. ## Computes the inverse secant of ``x``.
  302. proc arccsc*[T: float32|float64](x: T): T = arcsin(1.0 / x)
  303. ## Computes the inverse cosecant of ``x``.
  304. proc arccoth*[T: float32|float64](x: T): T = arctanh(1.0 / x)
  305. ## Computes the inverse hyperbolic cotangent of ``x``.
  306. proc arcsech*[T: float32|float64](x: T): T = arccosh(1.0 / x)
  307. ## Computes the inverse hyperbolic secant of ``x``.
  308. proc arccsch*[T: float32|float64](x: T): T = arcsinh(1.0 / x)
  309. ## Computes the inverse hyperbolic cosecant of ``x``.
  310. const windowsCC89 = defined(windows) and defined(bcc)
  311. when not defined(JS): # C
  312. proc hypot*(x, y: float32): float32 {.importc: "hypotf", header: "<math.h>".}
  313. proc hypot*(x, y: float64): float64 {.importc: "hypot", header: "<math.h>".}
  314. ## Computes the hypotenuse of a right-angle triangle with ``x`` and
  315. ## ``y`` as its base and height. Equivalent to ``sqrt(x*x + y*y)``.
  316. ##
  317. ## .. code-block:: nim
  318. ## echo hypot(4.0, 3.0) ## 5.0
  319. proc pow*(x, y: float32): float32 {.importc: "powf", header: "<math.h>".}
  320. proc pow*(x, y: float64): float64 {.importc: "pow", header: "<math.h>".}
  321. ## computes x to power raised of y.
  322. ##
  323. ## To compute power between integers, use ``^`` e.g. 2 ^ 6
  324. ##
  325. ## .. code-block:: nim
  326. ## echo pow(16.0, 0.5) ## 4.0
  327. # TODO: add C89 version on windows
  328. when not windowsCC89:
  329. proc erf*(x: float32): float32 {.importc: "erff", header: "<math.h>".}
  330. proc erf*(x: float64): float64 {.importc: "erf", header: "<math.h>".}
  331. ## Computes the `error function <https://en.wikipedia.org/wiki/Error_function>`_ for ``x``.
  332. proc erfc*(x: float32): float32 {.importc: "erfcf", header: "<math.h>".}
  333. proc erfc*(x: float64): float64 {.importc: "erfc", header: "<math.h>".}
  334. ## Computes the `complementary error function <https://en.wikipedia.org/wiki/Error_function#Complementary_error_function>`_ for ``x``.
  335. proc gamma*(x: float32): float32 {.importc: "tgammaf", header: "<math.h>".}
  336. proc gamma*(x: float64): float64 {.importc: "tgamma", header: "<math.h>".}
  337. ## Computes the the `gamma function <https://en.wikipedia.org/wiki/Gamma_function>`_ for ``x``.
  338. proc tgamma*(x: float32): float32
  339. {.deprecated: "use gamma instead", importc: "tgammaf", header: "<math.h>".}
  340. proc tgamma*(x: float64): float64
  341. {.deprecated: "use gamma instead", importc: "tgamma", header: "<math.h>".}
  342. ## The gamma function
  343. ## **Deprecated since version 0.19.0**: Use ``gamma`` instead.
  344. proc lgamma*(x: float32): float32 {.importc: "lgammaf", header: "<math.h>".}
  345. proc lgamma*(x: float64): float64 {.importc: "lgamma", header: "<math.h>".}
  346. ## Computes the natural log of the gamma function for ``x``.
  347. proc floor*(x: float32): float32 {.importc: "floorf", header: "<math.h>".}
  348. proc floor*(x: float64): float64 {.importc: "floor", header: "<math.h>".}
  349. ## Computes the floor function (i.e., the largest integer not greater than ``x``).
  350. ##
  351. ## .. code-block:: nim
  352. ## echo floor(-3.5) ## -4.0
  353. proc ceil*(x: float32): float32 {.importc: "ceilf", header: "<math.h>".}
  354. proc ceil*(x: float64): float64 {.importc: "ceil", header: "<math.h>".}
  355. ## Computes the ceiling function (i.e., the smallest integer not less than ``x``).
  356. ##
  357. ## .. code-block:: nim
  358. ## echo ceil(-2.1) ## -2.0
  359. when windowsCC89:
  360. # MSVC 2010 don't have trunc/truncf
  361. # this implementation was inspired by Go-lang Math.Trunc
  362. proc truncImpl(f: float64): float64 =
  363. const
  364. mask : uint64 = 0x7FF
  365. shift: uint64 = 64 - 12
  366. bias : uint64 = 0x3FF
  367. if f < 1:
  368. if f < 0: return -truncImpl(-f)
  369. elif f == 0: return f # Return -0 when f == -0
  370. else: return 0
  371. var x = cast[uint64](f)
  372. let e = (x shr shift) and mask - bias
  373. # Keep the top 12+e bits, the integer part; clear the rest.
  374. if e < 64-12:
  375. x = x and (not (1'u64 shl (64'u64-12'u64-e) - 1'u64))
  376. result = cast[float64](x)
  377. proc truncImpl(f: float32): float32 =
  378. const
  379. mask : uint32 = 0xFF
  380. shift: uint32 = 32 - 9
  381. bias : uint32 = 0x7F
  382. if f < 1:
  383. if f < 0: return -truncImpl(-f)
  384. elif f == 0: return f # Return -0 when f == -0
  385. else: return 0
  386. var x = cast[uint32](f)
  387. let e = (x shr shift) and mask - bias
  388. # Keep the top 9+e bits, the integer part; clear the rest.
  389. if e < 32-9:
  390. x = x and (not (1'u32 shl (32'u32-9'u32-e) - 1'u32))
  391. result = cast[float32](x)
  392. proc trunc*(x: float64): float64 =
  393. if classify(x) in {fcZero, fcNegZero, fcNan, fcInf, fcNegInf}: return x
  394. result = truncImpl(x)
  395. proc trunc*(x: float32): float32 =
  396. if classify(x) in {fcZero, fcNegZero, fcNan, fcInf, fcNegInf}: return x
  397. result = truncImpl(x)
  398. proc round*[T: float32|float64](x: T): T =
  399. ## Windows compilers prior to MSVC 2012 do not implement 'round',
  400. ## 'roundl' or 'roundf'.
  401. result = if x < 0.0: ceil(x - T(0.5)) else: floor(x + T(0.5))
  402. else:
  403. proc round*(x: float32): float32 {.importc: "roundf", header: "<math.h>".}
  404. proc round*(x: float64): float64 {.importc: "round", header: "<math.h>".}
  405. ## Rounds a float to zero decimal places. Used internally by the round
  406. ## function when the specified number of places is 0.
  407. proc trunc*(x: float32): float32 {.importc: "truncf", header: "<math.h>".}
  408. proc trunc*(x: float64): float64 {.importc: "trunc", header: "<math.h>".}
  409. ## Truncates ``x`` to the decimal point.
  410. ##
  411. ## .. code-block:: nim
  412. ## echo trunc(PI) # 3.0
  413. ## echo trunc(-1.85) # -1.0
  414. proc fmod*(x, y: float32): float32 {.deprecated: "use mod instead", importc: "fmodf", header: "<math.h>".}
  415. proc fmod*(x, y: float64): float64 {.deprecated: "use mod instead", importc: "fmod", header: "<math.h>".}
  416. ## Computes the remainder of ``x`` divided by ``y``.
  417. ## **Deprecated since version 0.19.0**: Use the ``mod`` operator instead.
  418. proc `mod`*(x, y: float32): float32 {.importc: "fmodf", header: "<math.h>".}
  419. proc `mod`*(x, y: float64): float64 {.importc: "fmod", header: "<math.h>".}
  420. ## Computes the modulo operation for float values (the remainder of ``x`` divided by ``y``).
  421. ##
  422. ## .. code-block:: nim
  423. ## ( 6.5 mod 2.5) == 1.5
  424. ## (-6.5 mod 2.5) == -1.5
  425. ## ( 6.5 mod -2.5) == 1.5
  426. ## (-6.5 mod -2.5) == -1.5
  427. else: # JS
  428. proc hypot*(x, y: float32): float32 {.importc: "Math.hypot", varargs, nodecl.}
  429. proc hypot*(x, y: float64): float64 {.importc: "Math.hypot", varargs, nodecl.}
  430. proc pow*(x, y: float32): float32 {.importC: "Math.pow", nodecl.}
  431. proc pow*(x, y: float64): float64 {.importc: "Math.pow", nodecl.}
  432. proc floor*(x: float32): float32 {.importc: "Math.floor", nodecl.}
  433. proc floor*(x: float64): float64 {.importc: "Math.floor", nodecl.}
  434. proc ceil*(x: float32): float32 {.importc: "Math.ceil", nodecl.}
  435. proc ceil*(x: float64): float64 {.importc: "Math.ceil", nodecl.}
  436. proc round*(x: float): float {.importc: "Math.round", nodecl.}
  437. proc trunc*(x: float32): float32 {.importc: "Math.trunc", nodecl.}
  438. proc trunc*(x: float64): float64 {.importc: "Math.trunc", nodecl.}
  439. proc `mod`*(x, y: float32): float32 {.importcpp: "# % #".}
  440. proc `mod`*(x, y: float64): float64 {.importcpp: "# % #".}
  441. ## Computes the modulo operation for float values (the remainder of ``x`` divided by ``y``).
  442. ##
  443. ## .. code-block:: nim
  444. ## ( 6.5 mod 2.5) == 1.5
  445. ## (-6.5 mod 2.5) == -1.5
  446. ## ( 6.5 mod -2.5) == 1.5
  447. ## (-6.5 mod -2.5) == -1.5
  448. proc round*[T: float32|float64](x: T, places: int): T {.deprecated: "use format instead".} =
  449. ## Decimal rounding on a binary floating point number.
  450. ##
  451. ## This function is NOT reliable. Floating point numbers cannot hold
  452. ## non integer decimals precisely. If ``places`` is 0 (or omitted),
  453. ## round to the nearest integral value following normal mathematical
  454. ## rounding rules (e.g. ``round(54.5) -> 55.0``). If ``places`` is
  455. ## greater than 0, round to the given number of decimal places,
  456. ## e.g. ``round(54.346, 2) -> 54.350000000000001421...``. If ``places`` is negative, round
  457. ## to the left of the decimal place, e.g. ``round(537.345, -1) ->
  458. ## 540.0``
  459. if places == 0:
  460. result = round(x)
  461. else:
  462. var mult = pow(10.0, places.T)
  463. result = round(x*mult)/mult
  464. proc floorDiv*[T: SomeInteger](x, y: T): T =
  465. ## Floor division is conceptually defined as ``floor(x / y)``.
  466. ## This is different from the ``div`` operator, which is defined
  467. ## as ``trunc(x / y)``. That is, ``div`` rounds towards ``0`` and ``floorDiv``
  468. ## rounds down.
  469. ##
  470. ## .. code-block:: nim
  471. ## echo floorDiv( 13, 3) # 4
  472. ## echo floorDiv(-13, 3) # -5
  473. ## echo floorDiv( 13, -3) # -5
  474. ## echo floorDiv(-13, -3) # 4
  475. result = x div y
  476. let r = x mod y
  477. if (r > 0 and y < 0) or (r < 0 and y > 0): result.dec 1
  478. proc floorMod*[T: SomeNumber](x, y: T): T =
  479. ## Floor modulus is conceptually defined as ``x - (floorDiv(x, y) * y)``.
  480. ## This proc behaves the same as the ``%`` operator in Python.
  481. ##
  482. ## .. code-block:: nim
  483. ## echo floorMod( 13, 3) # 1
  484. ## echo floorMod(-13, 3) # 2
  485. ## echo floorMod( 13, -3) # -2
  486. ## echo floorMod(-13, -3) # -1
  487. result = x mod y
  488. if (result > 0 and y < 0) or (result < 0 and y > 0): result += y
  489. when not defined(JS):
  490. proc c_frexp*(x: float32, exponent: var int32): float32 {.
  491. importc: "frexp", header: "<math.h>".}
  492. proc c_frexp*(x: float64, exponent: var int32): float64 {.
  493. importc: "frexp", header: "<math.h>".}
  494. proc frexp*[T, U](x: T, exponent: var U): T =
  495. ## Split a number into mantissa and exponent.
  496. ## ``frexp`` calculates the mantissa m (a float greater than or equal to 0.5
  497. ## and less than 1) and the integer value n such that ``x`` (the original
  498. ## float value) equals ``m * 2**n``. frexp stores n in `exponent` and returns
  499. ## m.
  500. ##
  501. ## .. code-block:: nim
  502. ## var x : int
  503. ## echo frexp(5.0, x) # 0.625
  504. ## echo x # 3
  505. var exp: int32
  506. result = c_frexp(x, exp)
  507. exponent = exp
  508. when windowsCC89:
  509. # taken from Go-lang Math.Log2
  510. const ln2 = 0.693147180559945309417232121458176568075500134360255254120680009
  511. template log2Impl[T](x: T): T =
  512. var exp: int32
  513. var frac = frexp(x, exp)
  514. # Make sure exact powers of two give an exact answer.
  515. # Don't depend on Log(0.5)*(1/Ln2)+exp being exactly exp-1.
  516. if frac == 0.5: return T(exp - 1)
  517. log10(frac)*(1/ln2) + T(exp)
  518. proc log2*(x: float32): float32 = log2Impl(x)
  519. proc log2*(x: float64): float64 = log2Impl(x)
  520. ## Log2 returns the binary logarithm of x.
  521. ## The special cases are the same as for Log.
  522. else:
  523. proc log2*(x: float32): float32 {.importc: "log2f", header: "<math.h>".}
  524. proc log2*(x: float64): float64 {.importc: "log2", header: "<math.h>".}
  525. ## Computes the binary logarithm (base 2) of ``x``
  526. else:
  527. proc frexp*[T: float32|float64](x: T, exponent: var int): T =
  528. if x == 0.0:
  529. exponent = 0
  530. result = 0.0
  531. elif x < 0.0:
  532. result = -frexp(-x, exponent)
  533. else:
  534. var ex = trunc(log2(x))
  535. exponent = int(ex)
  536. result = x / pow(2.0, ex)
  537. if abs(result) >= 1:
  538. inc(exponent)
  539. result = result / 2
  540. if exponent == 1024 and result == 0.0:
  541. result = 0.99999999999999988898
  542. proc splitDecimal*[T: float32|float64](x: T): tuple[intpart: T, floatpart: T] =
  543. ## Breaks ``x`` into an integer and a fractional part.
  544. ##
  545. ## Returns a tuple containing ``intpart`` and ``floatpart`` representing
  546. ## the integer part and the fractional part respectively.
  547. ##
  548. ## Both parts have the same sign as ``x``. Analogous to the ``modf``
  549. ## function in C.
  550. ##
  551. ## .. code-block:: nim
  552. ## echo splitDecimal(5.25) # (intpart: 5.0, floatpart: 0.25)
  553. var
  554. absolute: T
  555. absolute = abs(x)
  556. result.intpart = floor(absolute)
  557. result.floatpart = absolute - result.intpart
  558. if x < 0:
  559. result.intpart = -result.intpart
  560. result.floatpart = -result.floatpart
  561. {.pop.}
  562. proc degToRad*[T: float32|float64](d: T): T {.inline.} =
  563. ## Convert from degrees to radians
  564. ##
  565. ## .. code-block:: nim
  566. ## echo degToRad(180.0) # 3.141592653589793
  567. result = T(d) * RadPerDeg
  568. proc radToDeg*[T: float32|float64](d: T): T {.inline.} =
  569. ## Convert from radians to degrees
  570. ## .. code-block:: nim
  571. ## echo degToRad(2 * PI) # 360.0
  572. result = T(d) / RadPerDeg
  573. proc sgn*[T: SomeNumber](x: T): int {.inline.} =
  574. ## Sign function. Returns -1 for negative numbers and ``NegInf``, 1 for
  575. ## positive numbers and ``Inf``, and 0 for positive zero, negative zero and
  576. ## ``NaN``.
  577. ##
  578. ## .. code-block:: nim
  579. ## echo sgn(-5) # 1
  580. ## echo sgn(-4.1) # -1
  581. ord(T(0) < x) - ord(x < T(0))
  582. {.pop.}
  583. {.pop.}
  584. proc `^`*[T](x: T, y: Natural): T =
  585. ## Computes ``x`` to the power ``y``. ``x`` must be non-negative, use
  586. ## `pow <#pow,float,float>`_ for negative exponents.
  587. ##
  588. ## .. code-block:: nim
  589. ## echo 2 ^ 3 # 8
  590. when compiles(y >= T(0)):
  591. assert y >= T(0)
  592. else:
  593. assert T(y) >= T(0)
  594. var (x, y) = (x, y)
  595. result = 1
  596. while true:
  597. if (y and 1) != 0:
  598. result *= x
  599. y = y shr 1
  600. if y == 0:
  601. break
  602. x *= x
  603. proc gcd*[T](x, y: T): T =
  604. ## Computes the greatest common (positive) divisor of ``x`` and ``y``.
  605. ## Note that for floats, the result cannot always be interpreted as
  606. ## "greatest decimal `z` such that ``z*N == x and z*M == y``
  607. ## where N and M are positive integers."
  608. var (x, y) = (x, y)
  609. while y != 0:
  610. x = x mod y
  611. swap x, y
  612. abs x
  613. proc gcd*(x, y: SomeInteger): SomeInteger =
  614. ## Computes the greatest common (positive) divisor of ``x`` and ``y``.
  615. ## Using binary GCD (aka Stein's) algorithm.
  616. ##
  617. ## .. code-block:: nim
  618. ## echo gcd(24, 30) # 6
  619. when x is SomeSignedInt:
  620. var x = abs(x)
  621. else:
  622. var x = x
  623. when y is SomeSignedInt:
  624. var y = abs(y)
  625. else:
  626. var y = y
  627. if x == 0:
  628. return y
  629. if y == 0:
  630. return x
  631. let shift = countTrailingZeroBits(x or y)
  632. y = y shr countTrailingZeroBits(y)
  633. while x != 0:
  634. x = x shr countTrailingZeroBits(x)
  635. if y > x:
  636. swap y, x
  637. x -= y
  638. y shl shift
  639. proc lcm*[T](x, y: T): T =
  640. ## Computes the least common multiple of ``x`` and ``y``.
  641. ##
  642. ## .. code-block:: nim
  643. ## echo lcm(24, 30) # 120
  644. x div gcd(x, y) * y
  645. when isMainModule and not defined(JS) and not windowsCC89:
  646. # Check for no side effect annotation
  647. proc mySqrt(num: float): float {.noSideEffect.} =
  648. return sqrt(num)
  649. # check gamma function
  650. assert(gamma(5.0) == 24.0) # 4!
  651. assert($tgamma(5.0) == $24.0) # 4!
  652. assert(lgamma(1.0) == 0.0) # ln(1.0) == 0.0
  653. assert(erf(6.0) > erf(5.0))
  654. assert(erfc(6.0) < erfc(5.0))
  655. when isMainModule:
  656. # Function for approximate comparison of floats
  657. proc `==~`(x, y: float): bool = (abs(x-y) < 1e-9)
  658. block: # prod
  659. doAssert prod([1, 2, 3, 4]) == 24
  660. doAssert prod([1.5, 3.4]) == 5.1
  661. let x: seq[float] = @[]
  662. doAssert prod(x) == 1.0
  663. block: # round() tests
  664. # Round to 0 decimal places
  665. doAssert round(54.652) ==~ 55.0
  666. doAssert round(54.352) ==~ 54.0
  667. doAssert round(-54.652) ==~ -55.0
  668. doAssert round(-54.352) ==~ -54.0
  669. doAssert round(0.0) ==~ 0.0
  670. # Round to positive decimal places
  671. doAssert round(-547.652, 1) ==~ -547.7
  672. doAssert round(547.652, 1) ==~ 547.7
  673. doAssert round(-547.652, 2) ==~ -547.65
  674. doAssert round(547.652, 2) ==~ 547.65
  675. # Round to negative decimal places
  676. doAssert round(547.652, -1) ==~ 550.0
  677. doAssert round(547.652, -2) ==~ 500.0
  678. doAssert round(547.652, -3) ==~ 1000.0
  679. doAssert round(547.652, -4) ==~ 0.0
  680. doAssert round(-547.652, -1) ==~ -550.0
  681. doAssert round(-547.652, -2) ==~ -500.0
  682. doAssert round(-547.652, -3) ==~ -1000.0
  683. doAssert round(-547.652, -4) ==~ 0.0
  684. block: # splitDecimal() tests
  685. doAssert splitDecimal(54.674).intpart ==~ 54.0
  686. doAssert splitDecimal(54.674).floatpart ==~ 0.674
  687. doAssert splitDecimal(-693.4356).intpart ==~ -693.0
  688. doAssert splitDecimal(-693.4356).floatpart ==~ -0.4356
  689. doAssert splitDecimal(0.0).intpart ==~ 0.0
  690. doAssert splitDecimal(0.0).floatpart ==~ 0.0
  691. block: # trunc tests for vcc
  692. doAssert(trunc(-1.1) == -1)
  693. doAssert(trunc(1.1) == 1)
  694. doAssert(trunc(-0.1) == -0)
  695. doAssert(trunc(0.1) == 0)
  696. #special case
  697. doAssert(classify(trunc(1e1000000)) == fcInf)
  698. doAssert(classify(trunc(-1e1000000)) == fcNegInf)
  699. doAssert(classify(trunc(0.0/0.0)) == fcNan)
  700. doAssert(classify(trunc(0.0)) == fcZero)
  701. #trick the compiler to produce signed zero
  702. let
  703. f_neg_one = -1.0
  704. f_zero = 0.0
  705. f_nan = f_zero / f_zero
  706. doAssert(classify(trunc(f_neg_one*f_zero)) == fcNegZero)
  707. doAssert(trunc(-1.1'f32) == -1)
  708. doAssert(trunc(1.1'f32) == 1)
  709. doAssert(trunc(-0.1'f32) == -0)
  710. doAssert(trunc(0.1'f32) == 0)
  711. doAssert(classify(trunc(1e1000000'f32)) == fcInf)
  712. doAssert(classify(trunc(-1e1000000'f32)) == fcNegInf)
  713. doAssert(classify(trunc(f_nan.float32)) == fcNan)
  714. doAssert(classify(trunc(0.0'f32)) == fcZero)
  715. block: # sgn() tests
  716. assert sgn(1'i8) == 1
  717. assert sgn(1'i16) == 1
  718. assert sgn(1'i32) == 1
  719. assert sgn(1'i64) == 1
  720. assert sgn(1'u8) == 1
  721. assert sgn(1'u16) == 1
  722. assert sgn(1'u32) == 1
  723. assert sgn(1'u64) == 1
  724. assert sgn(-12342.8844'f32) == -1
  725. assert sgn(123.9834'f64) == 1
  726. assert sgn(0'i32) == 0
  727. assert sgn(0'f32) == 0
  728. assert sgn(NegInf) == -1
  729. assert sgn(Inf) == 1
  730. assert sgn(NaN) == 0
  731. block: # fac() tests
  732. try:
  733. discard fac(-1)
  734. except AssertionError:
  735. discard
  736. doAssert fac(0) == 1
  737. doAssert fac(1) == 1
  738. doAssert fac(2) == 2
  739. doAssert fac(3) == 6
  740. doAssert fac(4) == 24
  741. block: # floorMod/floorDiv
  742. doAssert floorDiv(8, 3) == 2
  743. doAssert floorMod(8, 3) == 2
  744. doAssert floorDiv(8, -3) == -3
  745. doAssert floorMod(8, -3) == -1
  746. doAssert floorDiv(-8, 3) == -3
  747. doAssert floorMod(-8, 3) == 1
  748. doAssert floorDiv(-8, -3) == 2
  749. doAssert floorMod(-8, -3) == -2
  750. doAssert floorMod(8.0, -3.0) ==~ -1.0
  751. doAssert floorMod(-8.5, 3.0) ==~ 0.5
  752. block: # log
  753. doAssert log(4.0, 3.0) == ln(4.0) / ln(3.0)
  754. doAssert log2(8.0'f64) == 3.0'f64
  755. doAssert log2(4.0'f64) == 2.0'f64
  756. doAssert log2(2.0'f64) == 1.0'f64
  757. doAssert log2(1.0'f64) == 0.0'f64
  758. doAssert classify(log2(0.0'f64)) == fcNegInf
  759. doAssert log2(8.0'f32) == 3.0'f32
  760. doAssert log2(4.0'f32) == 2.0'f32
  761. doAssert log2(2.0'f32) == 1.0'f32
  762. doAssert log2(1.0'f32) == 0.0'f32
  763. doAssert classify(log2(0.0'f32)) == fcNegInf