diff options
author | Koki Fushimi <paalon1936@gmail.com> | 2018-06-05 07:24:34 +0900 |
---|---|---|
committer | Varriount <Varriount@users.noreply.github.com> | 2018-06-04 18:24:34 -0400 |
commit | a3e5242d31fa2ac86072534a7528468c7a6f257d (patch) | |
tree | 1cb4d545f6c59a64c5f9a6b9267e5fd1cf5a5387 /lib/pure | |
parent | 069a53ad4bff8a3160794360227eceb1fc37d8d8 (diff) | |
download | Nim-a3e5242d31fa2ac86072534a7528468c7a6f257d.tar.gz |
Add product proc (#7951)
* Add product proc * Update changelog
Diffstat (limited to 'lib/pure')
-rw-r--r-- | lib/pure/math.nim | 14 |
1 files changed, 13 insertions, 1 deletions
diff --git a/lib/pure/math.nim b/lib/pure/math.nim index 6be19a339..6658b6307 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -129,6 +129,12 @@ proc sum*[T](x: openArray[T]): T {.noSideEffect.} = ## If `x` is empty, 0 is returned. for i in items(x): result = result + i +proc prod*[T](x: openArray[T]): T {.noSideEffect.} = + ## Computes the product of the elements in ``x``. + ## If ``x`` is empty, 1 is returned. + result = 1.T + for i in items(x): result = result * i + {.push noSideEffect.} when not defined(JS): # C proc sqrt*(x: float32): float32 {.importc: "sqrtf", header: "<math.h>".} @@ -372,7 +378,7 @@ when not defined(JS): # C proc `mod`*(x, y: float32): float32 {.importc: "fmodf", header: "<math.h>".} proc `mod`*(x, y: float64): float64 {.importc: "fmod", header: "<math.h>".} - ## Computes the modulo operation for float operators. + ## Computes the modulo operation for float operators. else: # JS proc hypot*[T: float32|float64](x, y: T): T = return sqrt(x*x + y*y) proc pow*(x, y: float32): float32 {.importC: "Math.pow", nodecl.} @@ -560,6 +566,12 @@ when isMainModule: # Function for approximate comparison of floats proc `==~`(x, y: float): bool = (abs(x-y) < 1e-9) + block: # prod + doAssert prod([1, 2, 3, 4]) == 24 + doAssert prod([1.5, 3.4]) == 5.1 + let x: seq[float] = @[] + doAssert prod(x) == 1.0 + block: # round() tests # Round to 0 decimal places doAssert round(54.652) ==~ 55.0 |