Generalize variance to other types
This commit is contained in:
parent
d0ff06b8c1
commit
e76f54e059
1 changed files with 3 additions and 3 deletions
|
|
@ -122,13 +122,13 @@ proc mean*[T](x: openArray[T]): float {.noSideEffect.} =
|
||||||
## ``toFloat(x: T): float`` must be defined.
|
## ``toFloat(x: T): float`` must be defined.
|
||||||
result = toFloat(sum(x)) / toFloat(len(x))
|
result = toFloat(sum(x)) / toFloat(len(x))
|
||||||
|
|
||||||
proc variance*(x: openArray[float]): float {.noSideEffect.} =
|
proc variance*[T](x: openArray[T]): float {.noSideEffect.} =
|
||||||
## computes the variance of the elements in `x`.
|
## computes the variance of the elements in `x`.
|
||||||
## If `x` is empty, NaN is returned.
|
## If `x` is empty, NaN is returned.
|
||||||
result = 0.0
|
result = 0.0
|
||||||
var m = mean(x)
|
var m = mean(x)
|
||||||
for i in 0 .. high(x):
|
for i in items(x):
|
||||||
var diff = x[i] - m
|
var diff = toFloat(i) - m
|
||||||
result = result + diff*diff
|
result = result + diff*diff
|
||||||
result = result / toFloat(len(x))
|
result = result / toFloat(len(x))
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue