tags:

views:

69

answers:

2

Hello,
I have 2 class :

// point : (x, y)
@interface ICPoint : NSObject {
    NSInteger x;
    NSInteger y;
}

// line : y= ax + b
@interface ICLine : NSObject {
    float a;
    float b;
}

and this method:

// return the distance between a line and a point
-(NSInteger) distance:(ICPoint *)point {
    return fabs(-a*point.x +point.y - b) / sqrt(a*a + 1);
}

The formula seems right (based on wikipedia), but the results are wrong... why ?
Thanks !

Edit:

ICLine *line1 = [[ICLine alloc] initWithA:0.60 andB:11.25];
ICLine *line2 = [[ICLine alloc] initWithA:0.61 andB:-2.85];

ICPoint *point = [[ICPoint alloc] initWithX:41 andY:22];

[line1 distance:point]; // give 11, it's ok.
[line2 distance:point]; // give 24, it should be ~0...
A: 

formula is correct, but your check is not. "give 24, it should be ~0..." are you sure? plot this line and point and you will see that they are not close at all and formula gives correct result. for such tests use the set of data that you can verify yourself. try obvious values that you can measure by ruler on piece of paper.

Andrey
The point is (41, 22), the equation is y= 0.61x - 2.85, right?If in the formula i do x = 41, i get y=~22. So the point is on the line => the distance should be 0... no ?What am I missing?
micropsari
+1  A: 

I get, with an independent implementation, that the two tests should yield (before casting to NSInteger) ~11.87 and ~0.17. Thus the method should return 11 and 0, as the questioner states.

NSInteger x, y;
float a, b;
x = 41; y = 22;
a = 0.61f; b = -2.85f;
NSLog(@"result ", fabs(-a*x + y - b) / sqrt(a * a + 1));

shows that the method's guts are correct.

Are your initializers correct?

Frank Shearar
... I was doing -(id) initWithA:(NSInteger)a1 andB:(NSInteger)b1; insted of -(id) initWithA:(float)a1 andB:(float)b1; Thank you!
micropsari
I've done that too many times to admit :)
Frank Shearar