Constructive mathematics is naturally typed. -- Simon Thompson
Basic math routines for Nim.
Note that the trigonometric functions naturally operate on radians. The helper functions degToRad and radToDeg provide conversion between radians and degrees.
Example:
import std/math from std/fenv import epsilon from std/random import rand proc generateGaussianNoise(mu: float = 0.0, sigma: float = 1.0): (float, float) = # Generates values from a normal distribution. # Translated from https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform#Implementation. var u1: float var u2: float while true: u1 = rand(1.0) u2 = rand(1.0) if u1 > epsilon(float): break let mag = sigma * sqrt(-2 * ln(u1)) let z0 = mag * cos(2 * PI * u2) + mu let z1 = mag * sin(2 * PI * u2) + mu (z0, z1) echo generateGaussianNoise()This module is available for the JavaScript target.
See also
- complex module for complex numbers and their mathematical operations
- rationals module for rational numbers and their mathematical operations
- fenv module for handling of floating-point rounding and exceptions (overflow, zero-divide, etc.)
- random module for a fast and tiny random number generator
- stats module for statistical analysis
- strformat module for formatting floats for printing
- system module for some very basic and trivial math operators (shr, shl, xor, clamp, etc.)
Types
FloatClass = enum fcNormal, ## value is an ordinary nonzero floating point value fcSubnormal, ## value is a subnormal (a very small) floating point value fcZero, ## value is zero fcNegZero, ## value is the negative zero fcNan, ## value is Not a Number (NaN) fcInf, ## value is positive infinity fcNegInf ## value is negative infinity
- Describes the class a floating point value belongs to. This is the type that is returned by the classify func. Source Edit
Consts
MaxFloat32Precision = 8
- Maximum number of meaningful digits after the decimal point for Nim's float32 type. Source Edit
MaxFloat64Precision = 16
- Maximum number of meaningful digits after the decimal point for Nim's float64 type. Source Edit
MaxFloatPrecision = 16
- Maximum number of meaningful digits after the decimal point for Nim's float type. Source Edit
MinFloatNormal = 2.225073858507201e-308
- Smallest normal number for Nim's float type (= 2^-1022). Source Edit
Procs
func almostEqual[T: SomeFloat](x, y: T; unitsInLastPlace: Natural = 4): bool {. inline.}
-
Checks if two float values are almost equal, using the machine epsilon.
unitsInLastPlace is the max number of units in the last place difference tolerated when comparing two numbers. The larger the value, the more error is allowed. A 0 value means that two numbers must be exactly the same to be considered equal.
The machine epsilon has to be scaled to the magnitude of the values used and multiplied by the desired precision in ULPs unless the difference is subnormal.
Example:
doAssert almostEqual(PI, 3.14159265358979) doAssert almostEqual(Inf, Inf) doAssert not almostEqual(NaN, NaN)
Source Edit func arctan2(y, x: float32): float32 {.importc: "atan2f", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
- Source Edit
func arctan2(y, x: float64): float64 {.importc: "atan2", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
-
Calculate the arc tangent of y/x.
It produces correct results even when the resulting angle is near PI/2 or -PI/2 (x near 0).
See also:
Example:
doAssert almostEqual(arctan2(1.0, 0.0), PI / 2.0) doAssert almostEqual(radToDeg(arctan2(1.0, 0.0)), 90.0)
Source Edit func cbrt(x: float32): float32 {.importc: "cbrtf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
- Source Edit
func cbrt(x: float64): float64 {.importc: "cbrt", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
-
Computes the cube root of x.
See also:
- sqrt func for the square root
Example:
doAssert almostEqual(cbrt(8.0), 2.0) doAssert almostEqual(cbrt(2.197), 1.3) doAssert almostEqual(cbrt(-27.0), -3.0)
Source Edit func ceil(x: float32): float32 {.importc: "ceilf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
- Source Edit
func ceilDiv[T: SomeInteger](x, y: T): T {.inline.}
-
Ceil division is conceptually defined as ceil(x / y).
Assumes x >= 0 and y > 0 (and x + y - 1 <= high(T) if T is SomeUnsignedInt).
This is different from the system.div operator, which works like trunc(x / y). That is, div rounds towards 0 and ceilDiv rounds up.
This function has the above input limitation, because that allows the compiler to generate faster code and it is rarely used with negative values or unsigned integers close to high(T)/2. If you need a ceilDiv that works with any input, see: https://github.com/demotomohiro/divmath.
See also:
- system.div proc for integer division
- floorDiv func for integer division which rounds down.
Example:
assert ceilDiv(12, 3) == 4 assert ceilDiv(13, 3) == 5
Source Edit func clamp[T](val: T; bounds: Slice[T]): T {.inline.}
-
Like system.clamp, but takes a slice, so you can easily clamp within a range.
Example:
assert clamp(10, 1 .. 5) == 5 assert clamp(1, 1 .. 3) == 1 type A = enum a0, a1, a2, a3, a4, a5 assert a1.clamp(a2..a4) == a2 assert clamp((3, 0), (1, 0) .. (2, 9)) == (2, 9) doAssertRaises(AssertionDefect): discard clamp(1, 3..2) # invalid bounds
Source Edit func classify(x: float): FloatClass {....raises: [], tags: [], forbids: [].}
-
Classifies a floating point value.
Returns x's class as specified by the FloatClass enum. Doesn't work with --passc:-ffast-math.
Example:
doAssert classify(0.3) == fcNormal doAssert classify(0.0) == fcZero doAssert classify(0.3 / 0.0) == fcInf doAssert classify(-0.3 / 0.0) == fcNegInf doAssert classify(5.0e-324) == fcSubnormal
Source Edit func copySign[T: SomeFloat](x, y: T): T {.inline.}
-
Returns a value with the magnitude of x and the sign of y; this works even if x or y are NaN, infinity or zero, all of which can carry a sign.
Example:
doAssert copySign(10.0, 1.0) == 10.0 doAssert copySign(10.0, -1.0) == -10.0 doAssert copySign(-Inf, -0.0) == -Inf doAssert copySign(NaN, 1.0).isNaN doAssert copySign(1.0, copySign(NaN, -1.0)) == -1.0
Source Edit func cosh(x: float32): float32 {.importc: "coshf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
- Source Edit
func divmod[T: SomeInteger](x, y: T): (T, T) {.inline.}
-
Specialized instructions for computing both division and modulus. Return structure is: (quotient, remainder)
Example:
doAssert divmod(5, 2) == (2, 1) doAssert divmod(5, -3) == (-1, 2)
Source Edit func euclDiv[T: SomeInteger](x, y: T): T
-
Returns euclidean division of x by y.
Example:
doAssert euclDiv(13, 3) == 4 doAssert euclDiv(-13, 3) == -5 doAssert euclDiv(13, -3) == -4 doAssert euclDiv(-13, -3) == 5
Source Edit func euclMod[T: SomeNumber](x, y: T): T
-
Returns euclidean modulo of x by y. euclMod(x, y) is non-negative.
Example:
doAssert euclMod(13, 3) == 1 doAssert euclMod(-13, 3) == 2 doAssert euclMod(13, -3) == 1 doAssert euclMod(-13, -3) == 2
Source Edit func exp(x: float32): float32 {.importc: "expf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
- Source Edit
func floor(x: float32): float32 {.importc: "floorf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
- Source Edit
func floorDiv[T: SomeInteger](x, y: T): T
-
Floor division is conceptually defined as floor(x / y).
This is different from the system.div operator, which is defined as trunc(x / y). That is, div rounds towards 0 and floorDiv rounds down.
See also:
- system.div proc for integer division
- floorMod func for Python-like (% operator) behavior
Example:
doAssert floorDiv( 13, 3) == 4 doAssert floorDiv(-13, 3) == -5 doAssert floorDiv( 13, -3) == -5 doAssert floorDiv(-13, -3) == 4
Source Edit func floorMod[T: SomeNumber](x, y: T): T
-
Floor modulo is conceptually defined as x - (floorDiv(x, y) * y).
This func behaves the same as the % operator in Python.
See also:
Example:
doAssert floorMod( 13, 3) == 1 doAssert floorMod(-13, 3) == 2 doAssert floorMod( 13, -3) == -2 doAssert floorMod(-13, -3) == -1
Source Edit func frexp[T: float32 | float64](x: T): tuple[frac: T, exp: int] {.inline.}
-
Splits x into a normalized fraction frac and an integral power of 2 exp, such that abs(frac) in 0.5..<1 and x == frac * 2 ^ exp, except for special cases shown below.
Example:
doAssert frexp(8.0) == (0.5, 4) doAssert frexp(-8.0) == (-0.5, 4) doAssert frexp(0.0) == (0.0, 0) # special cases: when sizeof(int) == 8: doAssert frexp(-0.0).frac.signbit # signbit preserved for +-0 doAssert frexp(Inf).frac == Inf # +- Inf preserved doAssert frexp(NaN).frac.isNaN
Source Edit func gamma(x: float32): float32 {.importc: "tgammaf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
- Source Edit
func gamma(x: float64): float64 {.importc: "tgamma", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
-
Computes the gamma function for x.
Note: Not available for the JS backend.
See also:
- lgamma func for the natural logarithm of the gamma function
Example:
doAssert almostEqual(gamma(1.0), 1.0) doAssert almostEqual(gamma(4.0), 6.0) doAssert almostEqual(gamma(11.0), 3628800.0)
Source Edit func gcd(x, y: SomeInteger): SomeInteger
-
Computes the greatest common (positive) divisor of x and y, using the binary GCD (aka Stein's) algorithm.
See also:
Example:
doAssert gcd(12, 8) == 4 doAssert gcd(17, 63) == 1
Source Edit func gcd[T](x, y: T): T
-
Computes the greatest common (positive) divisor of x and y.
Note that for floats, the result cannot always be interpreted as "greatest decimal z such that z*N == x and z*M == y where N and M are positive integers".
See also:
Example:
doAssert gcd(13.5, 9.0) == 4.5
Source Edit func hypot(x, y: float32): float32 {.importc: "hypotf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
- Source Edit
func hypot(x, y: float64): float64 {.importc: "hypot", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
-
Computes the length of the hypotenuse of a right-angle triangle with x as its base and y as its height. Equivalent to sqrt(x*x + y*y).
Example:
doAssert almostEqual(hypot(3.0, 4.0), 5.0)
Source Edit func isPowerOfTwo(x: int): bool {....raises: [], tags: [], forbids: [].}
-
Returns true, if x is a power of two, false otherwise.
Zero and negative numbers are not a power of two.
See also:
Example:
doAssert isPowerOfTwo(16) doAssert not isPowerOfTwo(5) doAssert not isPowerOfTwo(0) doAssert not isPowerOfTwo(-16)
Source Edit func ln(x: float32): float32 {.importc: "logf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
- Source Edit
func ln(x: float64): float64 {.importc: "log", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
-
Computes the natural logarithm of x.
See also:
Example:
doAssert almostEqual(ln(exp(4.0)), 4.0) doAssert almostEqual(ln(1.0), 0.0) doAssert almostEqual(ln(0.0), -Inf) doAssert ln(-7.0).isNaN
Source Edit func log2(x: float32): float32 {.importc: "log2f", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
- Source Edit
func log2(x: float64): float64 {.importc: "log2", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
-
Computes the binary logarithm (base 2) of x.
See also:
Example:
doAssert almostEqual(log2(8.0), 3.0) doAssert almostEqual(log2(1.0), 0.0) doAssert almostEqual(log2(0.0), -Inf) doAssert log2(-2.0).isNaN
Source Edit func log10(x: float32): float32 {.importc: "log10f", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
- Source Edit
func `mod`(x, y: float32): float32 {.importc: "fmodf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
- Source Edit
func `mod`(x, y: float64): float64 {.importc: "fmod", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
-
Computes the modulo operation for float values (the remainder of x divided by y).
See also:
- floorMod func for Python-like (% operator) behavior
Example:
doAssert 6.5 mod 2.5 == 1.5 doAssert -6.5 mod 2.5 == -1.5 doAssert 6.5 mod -2.5 == 1.5 doAssert -6.5 mod -2.5 == -1.5
Source Edit func nextPowerOfTwo(x: int): int {....raises: [], tags: [], forbids: [].}
-
Returns x rounded up to the nearest power of two.
Zero and negative numbers get rounded up to 1.
See also:
Example:
doAssert nextPowerOfTwo(16) == 16 doAssert nextPowerOfTwo(5) == 8 doAssert nextPowerOfTwo(0) == 1 doAssert nextPowerOfTwo(-16) == 1
Source Edit func pow(x, y: float32): float32 {.importc: "powf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
- Source Edit
func pow(x, y: float64): float64 {.importc: "pow", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
-
Computes x raised to the power of y.
To compute the power between integers (e.g. 2^6), use the ^ func.
See also:
Example:
doAssert almostEqual(pow(100, 1.5), 1000.0) doAssert almostEqual(pow(16.0, 0.5), 4.0)
Source Edit func round(x: float32): float32 {.importc: "roundf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
- Source Edit
func round(x: float64): float64 {.importc: "round", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
-
Rounds a float to zero decimal places.
Used internally by the round func when the specified number of places is 0.
See also:
- round func for rounding to the specific number of decimal places
- floor func
- ceil func
- trunc func
Example:
doAssert round(3.4) == 3.0 doAssert round(3.5) == 4.0 doAssert round(4.5) == 5.0
Source Edit func round[T: float32 | float64](x: T; places: int): T
-
Decimal rounding on a binary floating point number.
This function is NOT reliable. Floating point numbers cannot hold non integer decimals precisely. If places is 0 (or omitted), round to the nearest integral value following normal mathematical rounding rules (e.g. round(54.5) -> 55.0). If places is greater than 0, round to the given number of decimal places, e.g. round(54.346, 2) -> 54.350000000000001421…. If places is negative, round to the left of the decimal place, e.g. round(537.345, -1) -> 540.0.
Example:
doAssert round(PI, 2) == 3.14 doAssert round(PI, 4) == 3.1416
Source Edit func sgn[T: SomeNumber](x: T): int {.inline.}
-
Sign function.
Returns:
- -1 for negative numbers and NegInf,
- 1 for positive numbers and Inf,
- 0 for positive zero, negative zero and NaN
Example:
doAssert sgn(5) == 1 doAssert sgn(0) == 0 doAssert sgn(-4.1) == -1
Source Edit func sinh(x: float32): float32 {.importc: "sinhf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
- Source Edit
func splitDecimal[T: float32 | float64](x: T): tuple[intpart: T, floatpart: T]
-
Breaks x into an integer and a fractional part.
Returns a tuple containing intpart and floatpart, representing the integer part and the fractional part, respectively.
Both parts have the same sign as x. Analogous to the modf function in C.
Example:
doAssert splitDecimal(5.25) == (intpart: 5.0, floatpart: 0.25) doAssert splitDecimal(-2.73) == (intpart: -2.0, floatpart: -0.73)
Source Edit func tanh(x: float32): float32 {.importc: "tanhf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
- Source Edit
func trunc(x: float32): float32 {.importc: "truncf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}
- Source Edit