We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProcessing DevelopmentCore,  Processing Development Environment (PDE) › PVector.angleDistance() returns NaN
Page Index Toggle Pages: 1
PVector.angleDistance() returns NaN (Read 3027 times)
PVector.angleDistance() returns NaN
Jun 9th, 2009, 6:33am
 
PVector.angleDistance() often returns NaN when finding the distance between equal vectors. At first I thought it was my rusty trig, but digging in, it seems to be a rounding error. The method uses PVector.mag() (which returns a float), and passes it to Math.acos(), which the Java APIs say returns NaN if the argument's absolute value is > 1.  

I wrote a simple sketch to verify, and was able to get past the NaN results by using a version of mag() which returns a double:

void setup() {
 // some offending vectors
 PVector[] vs = new PVector[4];
 vs[0] = new PVector(-1, -1);
 vs[1] = new PVector(1 , -1);
 vs[2] = new PVector(1 ,  1);
 vs[3] = new PVector(-1,  1);
 
 for (int i = 0; i < vs.length; i++) {
   println(vs[i] + "\t default: " + PVector.angleBetween(vs[i], vs[i]));
   println(vs[i] + "\t doubles: " + angleBetween(vs[i], vs[i]));
   println();
 }
}

double mag(PVector v) {
 return Math.sqrt(v.x*v.x + v.y*v.y);
}

float angleBetween(PVector v1, PVector v2) {
 double dot = v1.dot(v2);
 float theta = (float) Math.acos(dot / (mag(v1) * mag(v2)));
 return theta;
}

It prints:

[ -1.0, -1.0, 0.0 ]       default: NaN
[ -1.0, -1.0, 0.0 ]       doubles: 2.1073424E-8

[ 1.0, -1.0, 0.0 ]       default: NaN
[ 1.0, -1.0, 0.0 ]       doubles: 2.1073424E-8

[ 1.0, 1.0, 0.0 ]       default: NaN
[ 1.0, 1.0, 0.0 ]       doubles: 2.1073424E-8

[ -1.0, 1.0, 0.0 ]       default: NaN
[ -1.0, 1.0, 0.0 ]       doubles: 2.1073424E-8



Should this be fixed? Could PVector.angleDistance() use a private version of mag(), which returns a double? I plan on pulling down the code and building, but haven't quite yet...
Re: PVector.angleDistance() returns NaN
Reply #1 - Aug 13th, 2009, 6:07am
 
Please file this as a bug and I'll look into it, thanks.
Re: PVector.angleDistance() returns NaN
Reply #2 - Aug 31st, 2009, 10:37am
 
Done: Bug 1316.  Let me know if there's anything I can do to help fix it.

Thanks!
Page Index Toggle Pages: 1