improving the class Vector

I am not happy with my class Vector. Looking at my posts “Nautilus” and “self-similar fractals …” I realize that complex numbers and vectors should be put together with their methods, which are mostly mappings of the plane. In particular, “Nautilus” mixes up the complex logarithm as a conformal plane mapping together with mirror images of vectors. Further I have defined methods and functions for the same actions. This is somehow redundant and not economical. Thus I improved the class Vector. You find the code in the next post.

For example, to add two vectors b and c to an already existing vector a, one had to write

a.add(b);
a.add(c);

which is rather low-level and cumbersome. To create a new vector x as the sum of three vectors we used

Vector x=add(a,add(b,c));

which looks slightly better. But this might be expensive because each call of add(,) creates a new vector object. To improve on this, I write the “add” method with an extra return statement:

  Vector add(Vector v){
    x+=v.x;
    y+=v.y;
    return this;
  }

Now I can chain methods and do additions on a single line:

a.add(b).add(c);

Combinations with other operations are possible too. But now we have to be attentive. Do not forget, that “add” changes the value of the Vector a. To avoid this, we have to create a copy of a and write

Vector x=a.copy().add(b).add(c);

to get a new vector x as the sum of a,b and c without changing a. Also, calculations with several terms depending on the same variable need special care, like this iteration:

     z=z.copy().power(n).add(z.mult(c));

else the value of z would be changed in the second term. Now, this looks really better.

Mixing complex numbers and  vectors we can do rotations by multiplying. With

Vector b=new Vector(cos(phi),sin(phi));
a.mult(b);

we rotate the vector a by the angle phi. In the improved class Vector there are more methods for complex functions. They will be useful for image manipulation.

I hope that this new version of the class Vector really is an improvement.

This entry was posted in programming, Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s