Created
January 22, 2009 01:05
-
-
Save igrigorik/50365 to your computer and use it in GitHub Desktop.
common math functions
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
| class Array; def sum; inject( nil ) { |sum,x| sum ? sum+x : x }; end; end | |
| class Array; def mean; self.sum/self.size.to_f; end; end | |
| class Array; def variance; mean = self.mean; Math.sqrt(inject( nil ) { |var,x| var ? var+((x-mean)**2) : ((x-mean)**2)}/self.size.to_f); end; end | |
| # inputs a random variable, sets mean = 0 and variance = 1 | |
| def standardize_random_variable(x) | |
| mean = x.mean | |
| variance = x.variance | |
| x.map!{|a| (a-mean)/variance } | |
| end | |
| ## Distance Functions | |
| # Sum of (x-y)^2 | |
| def euclidean_squared_distance(a,b) | |
| b = b.to_a | |
| a = a.to_a | |
| sum_of_diff_sq = 0 | |
| (0...a.size).each { |i| sum_of_diff_sq+=((a[i].to_f-b[i].to_f)**2)} | |
| sum_of_diff_sq | |
| end | |
| # Square root of sum of (x-y)^2 | |
| def euclidean_distance(neighbor,xq) | |
| Math.sqrt(euclidean_squared_distance(neighbor,xq)) | |
| end | |
| # Sum of abs(x,y) | |
| def manhattan_distance(neighbor,xq) | |
| xq = xq.to_a | |
| abs_diff = 0 | |
| (0...xq.size).each { |i| abs_diff+=(Math.abs(xq[i].to_f-neighbor[i].to_f)} | |
| abs_diff | |
| end | |
| class Float | |
| def number_decimal_places | |
| self.to_s.length-2 | |
| end | |
| def to_fraction | |
| higher = 10**self.number_decimal_places | |
| lower = self*higher | |
| gcden = greatest_common_divisor(higher, lower) | |
| return (lower/gcden).round, (higher/gcden).round | |
| end | |
| private | |
| def greatest_common_divisor(a, b) | |
| while a%b != 0 | |
| a,b = b.round,(a%b).round | |
| end | |
| return b | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment