overflow and implementation concerns

  • Thread starter Thread starter emma middlebrook
  • Start date Start date
E

emma middlebrook

Hi

Here's a couple of functions that could do with a bit of a review! The
intent is pretty obvious but am worried about (whether I can do
anything about):

- the overflow in the multiplication steps
- the consequences of the cast to int in the 2nd function
- incorrect typing e.g. 2nd function returning an int - maybe should
be a double as well??

static double Distance(PointF pointOne, PointF pointTwo)
{
double dx = pointOne.X - pointTwo.X;
double dy = pointOne.Y - pointTwo.Y;
return Math.Sqrt(dx*dx + dy*dy);
}

static int Distance(Point pointOne, Point pointTwo)
{
double dx = pointOne.X - pointTwo.X;
double dy = pointOne.Y - pointTwo.Y;
return (int)Math.Sqrt(dx*dx + dy*dy);
}

Any help appreciated!

Emma Middlebrook
(e-mail address removed)
 
Emma,

In my opinion, you should only have one Distance method, which takes a
double and returns a double (or you can use Decimals, if you really have a
set of large numbers). The reason for this is that the square root of an
integral number is not always going to produce an integral number.

As for what you can do about overflow, the only way you can handle this
is by having the return value be a type that can handle the possible values,
given the input. Given that ultimately you are performing a square root
operation, the double return type should be fine.

However, you do have to worry about squaring the x and y coordinates of
the deltas to get the distance. If you have any OverflowExceptions being
thrown, it will be there.

Hope this helps.
 
Back
Top