DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone >

Variance, Mean, Normalizing Functions, Euclidean And Other Distances

Snippets Manager user avatar by
Snippets Manager
·
Feb. 10, 07 · · Code Snippet
Like (0)
Save
Tweet
804 Views

Join the DZone community and get the full member experience.

Join For Free
Here sum, mean and variance were inspired by the Peter's inline sum code:


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


If you want to normalize a random variable (array) so that mean = 0 and variance = 1, you can transform your array x by calling:

# 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


If you want to compute distance, call these functions between two arrays of data, a and b.


## 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 cityblock_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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How to Submit a Post to DZone
  • Composable Architecture
  • DZone's Article Submission Guidelines
  • Refactoring Java Application: Object-Oriented And Functional Approaches

Comments

Partner Resources

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo