Resolve things raised in https://github.com/nim-lang/Nim/issues/10081 ? (#10084)
* Resolve things raised in https://github.com/nim-lang/Nim/issues/10081 ? CDF is a standard ident in all things related to random numbers/sampling, and full words "cumulativeDistributionFunction" would be silly long, in this case, IMO. We use lowercase `cdf` to make it not look like a type, remove all looping from `sample` letting callers do it. Besides just side-stepping any `sampleSize` name choice, callers may want to filter out samples anyway which this makes slightly simpler. Also add two variants of `cumsum`, value return and in-place update distinguished by the var-ness of the first argument. Add tests for `int` and `float` for both `cumsum` and the new `sample`. (The sample tests exercise the value return mode of `cumsum`.) Functionality pre-this-PR `sample(a, w)` is now the almost as simple `for i in 0..<n: sample(a, w.cumsum)`, but this new code factoring is almost surely better. The statistical tests pass, as before. * Address Araq comment in https://github.com/nim-lang/Nim/pull/10084 We can always add in some `var` version later if desired to save memory, but this change now at least firms up the `sample` interface. * Rename `cumsum` -> `cumsummed` to honor NEP1 style. Re-instate `cumsum` as the in-place transformation. Test both in `tests/stdlib/tmath.nim` and use `cumsummed` in the example code for sample since that's a simpler example. * Fix requests from https://github.com/nim-lang/Nim/pull/10084 : example in lib/pure/math.nim and comment whitespace in lib/pure/random.nim
This commit is contained in:
parent
e87910197a
commit
7ac1fc81fd
3 changed files with 85 additions and 29 deletions
|
|
@ -163,6 +163,24 @@ proc prod*[T](x: openArray[T]): T {.noSideEffect.} =
|
|||
result = 1.T
|
||||
for i in items(x): result = result * i
|
||||
|
||||
proc cumsummed*[T](x: openArray[T]): seq[T] =
|
||||
## Return cumulative aka prefix summation of ``x``.
|
||||
##
|
||||
## .. code-block:: nim
|
||||
## var x = [1, 2, 3, 4]
|
||||
## echo x.cumsummed # [1, 3, 6, 10]
|
||||
result.setLen(x.len)
|
||||
result[0] = x[0]
|
||||
for i in 1 ..< x.len: result[i] = result[i-1] + x[i]
|
||||
|
||||
proc cumsum*[T](x: var openArray[T]) =
|
||||
## Transforms ``x`` in-place into its cumulative aka prefix summation.
|
||||
##
|
||||
## .. code-block:: nim
|
||||
## var x = [1, 2, 3, 4]
|
||||
## x.cumsum; echo x # [1, 3, 6, 10]
|
||||
for i in 1 ..< x.len: x[i] = x[i-1] + x[i]
|
||||
|
||||
{.push noSideEffect.}
|
||||
when not defined(JS): # C
|
||||
proc sqrt*(x: float32): float32 {.importc: "sqrtf", header: "<math.h>".}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue