SIBT COMP 125
The practical this week will focus on the class POINT which describes geometric points in a plane. Note that the function sqrt is made available by the inherit SINGLE_MATH clause, while MATH_CONST contains the constant Pi (and the constant e as well).
class POINT -- geometric point in 2 dimensions inherit SINGLE_MATH; MATH_CONST creation make feature x : REAL -- x coordinate y : REAL -- y coordinate make( xc, yc : REAL) is -- create point (xc, yc) do x := xc y := yc end -- make move_to (new_x, new_y : REAL) is -- moves a point from old co-ordinates to new ones do x := new_x y := new_y end translate( a, b :REAL) is -- move point by a horizontally, and b vertically do x := x + a y := y + b end -- translate modulus : REAL is -- distance to the origin -- Uses sqrt from class SINGLE_MATH do Result := sqrt(x^2 + y^2) end -- modulus angle : REAL is -- angle to horizontal axis (in radians) -- range of angle is - Pi/2 to 3 Pi/2 do Result := arc_tangent(y / x) -- arc_tangent returns angle in range (-Pi/2 to Pi/2) -- test sign of x for angles between Pi/2 and 3 Pi/2 if x < 0.0 then Result := Result + Pi -- Pi from MATH_CONST end end -- angle distance( p : POINT) : REAL is -- distance between target point and argument point do Result := sqrt( (x-p.x)^2 + (y-p.y)^2 ) end -- angle output : STRING is -- a printable output for a point in form ( x, y) do -- append the parts to build up the string Result := "( " Result.append(x.out) -- x.out is x value in a STRING Result.append(", ") Result.append(y.out) -- y.out is y value in a STRING Result.append(")") end -- out end -- class POINT
In each case, I've just given the creation routine of the root-class of a test program that exercises the POINT class.
contains( p : POINT) : BOOLEAN
which shows whether the point argument is contained in the circle.