apscience
apscience

Reputation: 7273

AS3 - Y Velocity 6.123031769111886E-17

When given 0,0 to 0,5, the y velocity becomes that number and breaks my code. I know I must have done something wrong as I just copy and pasted code (since I am horrible at maths)..

This is how I calculate the numbers:

var radian = Math.atan2(listOfNodes[j].y - listOfNodes[i].y,listOfNodes[j].x - listOfNodes[i].x);
var vy = Math.cos(radian);
var vx = Math.sin(radian);

Thanks

Upvotes: 1

Views: 341

Answers (1)

danishgoel
danishgoel

Reputation: 3645

There i am assuming the velocity vector is FROM 0,0 TO 0,5. And 0,0 is i and 0,5 is j.

In that case the velocity vector is only along y and the y component should be 5 and x component 0. It is coming as opposite because,

cos(radian) whould be x velocity component and sin(radian) the y compunent.

And the number 6.123031769111886E-17 is actually returned in place of 0.

Look at the following figure:
enter image description here

Also as can be seen from the figure you do not need the trigonometric computations at all.
You can simply get the x and y components as follows:

// y2 - y1
var vy = listOfNodes[j].y - listOfNodes[i].y;
// x2 - x1
var vx = listOfNodes[j].x - listOfNodes[i].x;

This will avoid the floating point inaccuracy caused by the trig finctions due to which you are seeing 6.123031769111886E-17 instead of 0.
You only need to use atan2 if you actually need the angle θ in your code.

Update: Well if you need only unit (normalized) vector's components you can divide the vx and vy with the length of the original vector. Like this:

// y2 - y1
var vy = listOfNodes[j].y - listOfNodes[i].y;
// x2 - x1
var vx = listOfNodes[j].x - listOfNodes[i].x;
// vector magnitude
var mag = Math.sqrt(vx * vx + vy * vy);

// get unit vector components
vy /= mag;
vx /= mag;

Using the above you will get the exactly the same results as you are getting from trig sin and cos functions.

But if you still need to use the original code and want to make 6.12...E-17 compare to 0, you can use the epsilon technique for comparing floats. So you can compare any value within epsilon's range from 0, using flllowing code:

function floatCompare(a:Number, b:Number, epsilon:Number):Boolean{
    return (a >= (b - epsilon) && a <= (b + epsilon));
}
// To check for zero use this code, here i'm using 0.0001 as epsilon
if(floatCompare(vx, 0, 0.0001)){
    // code here
}

So any deviation in the range of [b-epsilon, b+epsilon] would successfully compare to b. This is essential in case of floating point arithmetic.

Upvotes: 5

Related Questions