Created
September 19, 2024 16:58
-
-
Save maxsei/f34d45a7fda82da67baa96a558094d69 to your computer and use it in GitHub Desktop.
welfords online variance algorithm
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
const std = @import("std"); | |
pub fn main() void { | |
const input1 = [_]f32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; | |
var mean: f32 = 0; | |
var variance: f32 = 0; | |
for (input1, 0..) |v, count| { | |
const delta = v - mean; | |
mean += delta / @as(f32, @floatFromInt(count + 1)); | |
const delta2 = v - mean; | |
variance += delta * delta2; | |
} | |
const stdev = std.math.sqrt(variance); | |
std.debug.print("{[mean]d:0.4} {[stdev]d:0.4}\n", .{ | |
.mean = mean, | |
.stdev = stdev, | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment