Dan Bernier
YaBB Newbies
Offline
Posts: 3
Bristol, CT, USA
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...