std/math
Source EditConstructive 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.)
Imports
- since, bitops, fenv, countbits_impl
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
float32type. Source Edit MaxFloat64Precision = 16
- Maximum number of meaningful digits after the decimal point for Nim's
float64type. Source Edit MaxFloatPrecision = 16
- Maximum number of meaningful digits after the decimal point for Nim's
floattype. 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.
unitsInLastPlaceis the max number of units in the last place difference tolerated when comparing two numbers. The larger the value, the more error is allowed. A0value 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: [].}- 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/2or-PI/2(xnear 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: [].}- Computes the binomial coefficient.
Example:
doAssert binom(6, 2) == 15 doAssert binom(-6, 2) == 1 doAssert binom(6, 0) == 1
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 >= 0andy > 0(andx + y - 1 <= high(T)if T is SomeUnsignedInt).This is different from the system.div operator, which works like
trunc(x / y). That is,divrounds towards0andceilDivrounds 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 aceilDivthat 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.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
xand the sign ofy; 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 cos(x: float32): float32 {.importc: "cosf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}- Source Edit
func cosh(x: float32): float32 {.importc: "coshf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}- Source Edit
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
xin-place (must be declared asvar) into its cumulative (aka prefix) summation.See also:
- sum func
- cumsummed func for a version which returns a cumsummed sequence
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
xis empty,@[]is returned.See also:
- sum func
- cumsum func for the in-place version
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: [].}- Source Edit
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 Edit func erfc(x: float32): float32 {.importc: "erfcf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}- Source Edit
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 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,divrounds towards0andfloorDivrounds 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
xinto a normalized fractionfracand an integral power of 2exp, such thatabs(frac) in 0.5..<1andx == 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
xandy, 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
xandy.Note that for floats, the result cannot always be interpreted as "greatest decimal
zsuch thatz*N == x and z*M == ywhere 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
xas its base andyas its height. Equivalent tosqrt(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, ifxis a power of two,falseotherwise.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: [].}- Source Edit
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:
- gamma func for gamma function
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
xdivided byy).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 -
floorMod func for Python-like (
func nextPowerOfTwo(x: int): int {....raises: [], tags: [], forbids: [].}-
Returns
xrounded 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
xraised to the power ofy.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
placesis 0 (or omitted), round to the nearest integral value following normal mathematical rounding rules (e.g.round(54.5) -> 55.0). Ifplacesis greater than 0, round to the given number of decimal places, e.g.round(54.346, 2) -> 54.350000000000001421…. Ifplacesis 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 sin(x: float32): float32 {.importc: "sinf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}- Source Edit
func sinh(x: float32): float32 {.importc: "sinhf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}- Source Edit
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
xinto an integer and a fractional part.Returns a tuple containing
intpartandfloatpart, representing the integer part and the fractional part, respectively.Both parts have the same sign as
x. Analogous to themodffunction 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: [].}- Source Edit
func tanh(x: float32): float32 {.importc: "tanhf", header: "<math.h>", ...raises: [], tags: [], forbids: [].}- Source Edit
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: [].}- Source Edit
© 2006–2024 Andreas Rumpf
Licensed under the MIT License.
https://nim-lang.org/docs/math.html