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. shr, shl, xor, clamp, etc.)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
MaxFloat32Precision = 8
float32 type. Source Edit MaxFloat64Precision = 16
float64 type. Source Edit MaxFloatPrecision = 16
float type. Source Edit 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 arctan(x: float32): float32 {.importc: "atanf", header: "<math.h>",
...raises: [], tags: [], forbids: [].}func arctan2(y, x: float32): float32 {.importc: "atan2f", header: "<math.h>",
...raises: [], tags: [], forbids: [].}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 binom(n, k: int): int {....raises: [], tags: [], forbids: [].}Example:
doAssert binom(6, 2) == 15 doAssert binom(-6, 2) == 1 doAssert binom(6, 0) == 1Source Edit
func cbrt(x: float32): float32 {.importc: "cbrtf", header: "<math.h>",
...raises: [], tags: [], forbids: [].}func cbrt(x: float64): float64 {.importc: "cbrt", header: "<math.h>",
...raises: [], tags: [], forbids: [].}Computes the cube root of x.
See also:
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: [].}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:
Example:
assert ceilDiv(12, 3) == 4 assert ceilDiv(13, 3) == 5Source Edit
func clamp[T](val: T; bounds: Slice[T]): T {.inline.}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 boundsSource Edit
func classify(x: float): FloatClass {....raises: [], tags: [], forbids: [].}Classifies a floating point value.
Returns x's class as specified by the FloatClass enum.
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) == fcSubnormalSource Edit
func copySign[T: SomeFloat](x, y: T): T {.inline.}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.0Source Edit
func cos(x: float32): float32 {.importc: "cosf", header: "<math.h>", ...raises: [],
tags: [], forbids: [].}func cosh(x: float32): float32 {.importc: "coshf", header: "<math.h>",
...raises: [], tags: [], forbids: [].}func cosh(x: float64): float64 {.importc: "cosh", header: "<math.h>",
...raises: [], tags: [], forbids: [].}Computes the hyperbolic cosine of x.
See also:
Example:
doAssert almostEqual(cosh(0.0), 1.0) doAssert almostEqual(cosh(1.0), 1.543080634815244)Source Edit
func cumsum[T](x: var openArray[T])
Transforms x in-place (must be declared as var) into its cumulative (aka prefix) summation.
See also:
Example:
var a = [1, 2, 3, 4] cumsum(a) doAssert a == @[1, 3, 6, 10]Source Edit
func cumsummed[T](x: openArray[T]): seq[T]
Returns the cumulative (aka prefix) summation of x.
If x is empty, @[] is returned.
See also:
Example:
doAssert cumsummed([1, 2, 3, 4]) == @[1, 3, 6, 10]Source Edit
func erf(x: float32): float32 {.importc: "erff", header: "<math.h>", ...raises: [],
tags: [], forbids: [].}func erf(x: float64): float64 {.importc: "erf", header: "<math.h>", ...raises: [],
tags: [], forbids: [].}Computes the error function for x.
Note: Not available for the JS backend.
Source Editfunc erfc(x: float32): float32 {.importc: "erfcf", header: "<math.h>",
...raises: [], tags: [], forbids: [].}func erfc(x: float64): float64 {.importc: "erfc", header: "<math.h>",
...raises: [], tags: [], forbids: [].}Computes the complementary error function for x.
Note: Not available for the JS backend.
Source Editfunc exp(x: float32): float32 {.importc: "expf", header: "<math.h>", ...raises: [],
tags: [], forbids: [].}func floor(x: float32): float32 {.importc: "floorf", header: "<math.h>",
...raises: [], tags: [], forbids: [].}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:
% operator) behaviorExample:
doAssert floorDiv( 13, 3) == 4 doAssert floorDiv(-13, 3) == -5 doAssert floorDiv( 13, -3) == -5 doAssert floorDiv(-13, -3) == 4Source 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) == -1Source Edit
func frexp[T: float32 | float64](x: T): tuple[frac: T, exp: int] {.inline.}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.isNaNSource Edit
func gamma(x: float32): float32 {.importc: "tgammaf", header: "<math.h>",
...raises: [], tags: [], forbids: [].}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:
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) == 1Source 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.5Source Edit
func hypot(x, y: float32): float32 {.importc: "hypotf", header: "<math.h>",
...raises: [], tags: [], forbids: [].}func hypot(x, y: float64): float64 {.importc: "hypot", header: "<math.h>",
...raises: [], tags: [], forbids: [].}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 lgamma(x: float32): float32 {.importc: "lgammaf", header: "<math.h>",
...raises: [], tags: [], forbids: [].}func lgamma(x: float64): float64 {.importc: "lgamma", header: "<math.h>",
...raises: [], tags: [], forbids: [].}Computes the natural logarithm of the gamma function for x.
Note: Not available for the JS backend.
See also:
func ln(x: float32): float32 {.importc: "logf", header: "<math.h>", ...raises: [],
tags: [], forbids: [].}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).isNaNSource Edit
func log2(x: float32): float32 {.importc: "log2f", header: "<math.h>",
...raises: [], tags: [], forbids: [].}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).isNaNSource Edit
func log10(x: float32): float32 {.importc: "log10f", header: "<math.h>",
...raises: [], tags: [], forbids: [].}func `mod`(x, y: float32): float32 {.importc: "fmodf", header: "<math.h>",
...raises: [], tags: [], forbids: [].}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:
% operator) behaviorExample:
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.5Source 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) == 1Source Edit
func pow(x, y: float32): float32 {.importc: "powf", header: "<math.h>",
...raises: [], tags: [], forbids: [].}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: [].}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:
Example:
doAssert round(3.4) == 3.0 doAssert round(3.5) == 4.0 doAssert round(4.5) == 5.0Source 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.1416Source Edit
func sin(x: float32): float32 {.importc: "sinf", header: "<math.h>", ...raises: [],
tags: [], forbids: [].}func sinh(x: float32): float32 {.importc: "sinhf", header: "<math.h>",
...raises: [], tags: [], forbids: [].}func sinh(x: float64): float64 {.importc: "sinh", header: "<math.h>",
...raises: [], tags: [], forbids: [].}Computes the hyperbolic sine of x.
See also:
Example:
doAssert almostEqual(sinh(0.0), 0.0) doAssert almostEqual(sinh(1.0), 1.175201193643801)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 tan(x: float32): float32 {.importc: "tanf", header: "<math.h>", ...raises: [],
tags: [], forbids: [].}func tanh(x: float32): float32 {.importc: "tanhf", header: "<math.h>",
...raises: [], tags: [], forbids: [].}func tanh(x: float64): float64 {.importc: "tanh", header: "<math.h>",
...raises: [], tags: [], forbids: [].}Computes the hyperbolic tangent of x.
See also:
Example:
doAssert almostEqual(tanh(0.0), 0.0) doAssert almostEqual(tanh(1.0), 0.7615941559557649)Source Edit
func trunc(x: float32): float32 {.importc: "truncf", header: "<math.h>",
...raises: [], tags: [], forbids: [].}
© 2006–2024 Andreas Rumpf
Licensed under the MIT License.
https://nim-lang.org/docs/math.html