Created
May 14, 2022 14:25
-
-
Save b0mbie/f9671b8414a0e438b1cc735ec5535a61 to your computer and use it in GitHub Desktop.
Iterative mean function for Lua
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| return function imean(m, v, i) | |
| return ((m * i) + v) / (i + 1) | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| local imean = require "imean" | |
| -- define the values to find the means of | |
| local values = { 2, 3, 4, 5 } | |
| -- get regular mean | |
| local m = 0 | |
| for i,x in ipairs(values) do m = m + x end | |
| m = m / #values | |
| -- get iterative mean | |
| local im | |
| for i,x in ipairs(values) do | |
| if i == 1 then | |
| im = x | |
| else | |
| im = imean(im, x, i - 1) | |
| end | |
| end | |
| -- assert iterative mean | |
| assert(im == m, im .. " is not equal to " .. m) | |
| -- test results | |
| local valuesString = table.concat(values, ", ") | |
| print(string.format("the calculated mean of %s: %.2f", valuesString, m)) | |
| print(string.format("the calculated iterative mean of %s: %.2f", valuesString, im)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment