Skip to content

Instantly share code, notes, and snippets.

@cihat645
Last active May 20, 2017 21:32
Show Gist options
  • Save cihat645/303736f5462dea26caf52e2e592981e6 to your computer and use it in GitHub Desktop.
Save cihat645/303736f5462dea26caf52e2e592981e6 to your computer and use it in GitHub Desktop.
A simple function that calculates linear regression lines in Swift
//
// main.swift
// LinearRegression
//
// Created by Thomas Ciha on 5/20/17.
// Copyright © 2017 Thomas Ciha. All rights reserved.
//
import Foundation
//write an algorithm that calculates a linear regression line for a set of data
func calculateLine(data: Double...) -> String{
if(data.count % 2 != 0){
return "Unable to calculate, missing a y-value"
}
var x = 0.0, y = 0.0, xy = 0.0, x2 = 0.0, m : Double, index = 0
for value in data{
if(index % 2 == 0){ //if even index, it's an x-value
x += value
xy += value * data[index + 1]
x2 += value * value
}
else { //if odd index, it's a y-value
y += value
}
index += 1
}
let num_of_xy_pairs = Double(data.count / 2)
x /= num_of_xy_pairs
y /= num_of_xy_pairs
xy /= num_of_xy_pairs
x2 /= num_of_xy_pairs
m = round((x * y - xy) / ((x * x) - x2) * 1000) / 1000
let b = round((y - m * x) * 1000) / 1000
if(b < 0){
return "y = \(m)x \(b)"
}
else{
return "y = \(m)x + \(b)"
}
}
print(calculateLine(data: 17,23,123,7,4,6,9,10,11,12))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment