Unusually clear pseudocode example
- Posted by DB James <larch at adelphia.net> Oct 24, 2005
- 463 views
Hi, Found this on the web while searching on "pseudocode" -- it seems like a good clear example of a presention of an algorithm. A collection of such algorithms, done consistently in form, would be valuable. As it is, the pseudocode on the web seems a mish-mash that ranges widely in value. Even this example is mildly biased toward C++. Ideally there would be no program bias. I did use this in writing a slope and intercept function. ------------------------------------------------------------------ from: http://www.mines.edu/Academic/courses/math_cs/macs261/LABS/F00/lab7.html LEAST SQUARES LINE PURPOSE: Find the equation of the least squares line for a set of n data points (x,y). Slope is its slope, and YIntercept it its y intercept. SumX, SumY, SumX2, and SumXY are the sums of the x's, the y's, the squares of the x's, and the products x*y. XMean and YMean are the means of the x's and the y's, respectively INPUT: A collection of data points (x,y) OUTPUT: The equation of the least squares line ALGORITHM: Step 1 Initialize n, SumX, SumY, SumX2, SumXY all to 0. Step 2 Read the x-coordinate of the first data point x. Step 3 While the end of data has not been encountered, do the following Step 4 Read the y-coordinate of the data point, y. Step 5 Increment n by 1. Step 6 Add x to SumX Step 7 Add x^2 to SumX2 Step 8 Add y to SumY Step 9 Add x*y to SumXY Step 10 Read the next data point x,y End while Step 11 If n > 0 then call CalculateSlopeIntercept and display least squares line Step 12 Else Display a message that no data points were read. End If/Else End Main PROCEDURE: CalculateSlopeIntercept INPUT: SumX, SumY, SumX2, SumXY, n OUTPUT: Slope of least squares line, and YIntercept of least squares line. ALGORITHM: Step1 calculate XMean = SumX/n and YMean = SumY/n Step2 calculate Slope = (SumXY - SumX*YMean)/(SumX2 - SumX*XMean) Step3 calculate YIntercept = YMean - Slope * XMean Step4 return Slope and YIntercept The algorithm assumes a main portion and a function call to a procedure called ComputeSlopeIntercept. In C++ this would be a main() function and a void function ComputeSlopeIntercept with 5 value parameters and 2 reference parameters. Step 4 in the procedure algorithm, return Slope and YIntercept is achieved through assignment of the reference parameters. No explicit return statement is needed. The output of the program is bracketed by an if/else structure to avoid calling the procedure ComputeSlopeIntercept with no data points. The output should include the format of a line in slope-intercept form y = mx + b. This equation should be displayed on the screen. ---------------------------------------------------------------------- --Quark