← ppnm

Exercise "vec"

Tasks:

  1. Start with something like

    public class vec{
    	public double x,y,z; /* the three components of a vector */
    	/* your stuff goes here */
    }
    
  2. Implement a couple of constructors,
    //constructors:
    public vec(){ x=y=z=0; }
    public vec(double x,double y,double z){ this.x=x; this.y=y; this.z=z; }
    
  3. Overload mathematical operators,
    //operators:
    public static vec operator*(vec v, double c){return new vec(c*v.x,c*v.y,c*v.z);}
    public static vec operator*(double c, vec v){return v*c;}
    public static vec operator+(vec u, vec v){/*...*/}
    public static vec operator-(vec u){return new vec(-u.x,-u.y,-u.z)}
    public static vec operator-(vec u, vec v){/*...*/}
    
  4. Make a "print" method for debugging,
    //methods:
    public void print(string s){Write(s);WriteLine($"{x} {y} {z}");}
    public void print(){this.print("");}
    
  5. Implement methods for dot-product, vector-product, and norm. Something like

    public double dot(vec other) /* to be called as u.dot(v) */
    	{return this.x*other.x+this.y*other.y+this.z*other.z;}
    public static double dot(vec v,vec w) /* to be called as vec.dot(u,v) */
    	{return v.x*w.x+v.y*w.y+v.z*w.z;}
    
    You can also try this C# syntactic sugar,
    public double dot(vec other) => this.x*other.x+this.y*other.y+this.z*other.z;
    public static double dot(vec v,vec w) => v.x*w.x+v.y*w.y+v.z*w.z;
    
  6. Make an "approx" method to compare two vec's with absolute precision "acc" and relative precision "eps". Something like

    static bool approx(double a,double b,double acc=1e-9,double eps=1e-9){
    	if(Abs(a-b)<acc)return true;
    	if(Abs(a-b)<(Abs(a)+Abs(b))*eps)return true;
    	return false;
    	}
    public bool approx(vec other){
    	if(!approx(this.x,other.x)return false;
    	if(!approx(this.y,other.y)return false;
    	if(!approx(this.z,other.z)return false;
    	return true;
    	}
    public static bool approx(vec u, vec v) => u.approx(v);
    
  7. Override ToString method, something like
    public override string ToString(){ return $"{x} {y} {z}"; }
    	
  8. Put your "vec" class in the file "vec.cs" and compile it into a library,
    vec.dll: vec.cs
    	mcs -target:library -out:vec.dll vec.cs
    
    Create a "main.cs" file with the "Main" function that illustrates your implementation and link it with "vec.dll" like this,
    main.exe: main.cs vec.dll
    	mcs -target:exe -out:main.exe -reference:vec.dll main.cs
    
  9. Run extensive tests of your implementation in the Main function (see [../matlib/complex/main.cs] for inspiration).