linear_least_square


This humbly-named little program went from a single function for line-fitting multiple data-points to an entire workbench for completing my geography project (coded in August 2009). The idea behind the project was to figure out the warming factor in terms of latitude. Before this was found, the altitude correction for temperature needed to be extracted.

Note: rather than writing my own CSV parser, Python’s CSV module could’ve been used.

def getLinearLeast(points):
    #split it up into two lists
    xpoints = []
    ypoints = []
    for point in points:
        xpoints.append(point[0])
        ypoints.append(point[1])
    numerator1 = (sum(i**2.0 for i in xpoints) * sum(ypoints)) - (sum(xpoints) * sum(xpoints[i]*ypoints[i] for i in range(len(xpoints))))
    numerator2 = len(xpoints)*sum(xpoints[i]*ypoints[i] for i in range(len(xpoints))) - (sum(xpoints)*sum(ypoints))
    denominator = len(xpoints)*(sum(i**2.0 for i in xpoints)) - (sum(xpoints))**2.0
    intercept = numerator1/denominator
    slope = numerator2/denominator
    return intercept, slope

def ReadCSV(filename,delimiter=","):
    ret = []
    f = open(filename)
    lines = f.readlines()
    f.close()
    for line in lines:
        elements = line.split(delimiter)
        ret.append(elements)
    return ret

def WriteCSV(filename,data,delimiter=","):
    out = ""
    for line in data:
        for i in range(len(line)):
            out+=str(line[i])
            if i != len(line)-1:
                out+=","
        out+="n"
    f = open(filename, "w")
    f.write(out)
    f.close()

def ChooseCSVColumns(csvlist, desiredcols):
    ret = []
    for csvitem in csvlist:
        line = []
        for desiredcol in desiredcols:
            item = csvitem[desiredcol]
            if not item.count("""): #not a string
                item = float(item)
            line.append(item)
        ret.append(line)
    return ret

#Altitude
#points = ChooseCSVColumns(ReadCSV("temp_vs_elev_one_lat_MO_through_CO.csv"), [0,2])
#print points
#print getLinearLeast([[0,0],[2,2]])
#print getLinearLeast(points)

#feet vs temp slope is about -0.0014 for Jan and 4 for summer and -0.00193 for Jul

#Altitude correction
#table = ChooseCSVColumns(ReadCSV("Temp_Lat_Graph_and_elev.csv"),[0,1,2,3])
#for i in range(len(table)):
#    table[i][1] = table[i][1]-(table[i][3]*-0.0014) #Jan factor
#    table[i][2] = table[i][2]-(table[i][3]*-0.00193) #Jul factor

#WriteCSV("corrected.csv", table)

points = ChooseCSVColumns(ReadCSV("corrected.csv"), [0,2])
print getLinearLeast(points)

#tropic of cancer 23.434 degrees

Posted in: Code by nsundin
Copyright © 2011-2025 Programmatic Verse · RSS Feed
Built on Skeleton
Powerered by Wordpress