5
There i am assuming the velocity vector is FROM 0,0 TO 0,5. And 0,0 is i and 0,5 is j.
我假设速度向量是从0到0 5。0 0是i 5是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,
在这种情况下,速度矢量只沿y方向,y分量应该是5,x分量是0。因为,
cos(radian)
whould be x velocity component and sin(radian)
the y compunent.
因为(radian)应该是x速度分量,sin(radian)是y的compunent。
And the number 6.123031769111886E-17 is actually returned in place of 0.
而数字6.123031769111886E-17实际上返回的是0。
Look at the following figure:
请看下图:
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:
同样,从图中可以看出,你根本不需要三角计算。你可以简单地得到x和y分量如下:
// 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.
这将避免由trig finctions引起的浮点不准确,因为您看到的是6.123031769111886E-17而不是0。你只需要使用量化如果你真的需要角θ在您的代码中。
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:
更新:如果你只需要单位(归一化)向量的分量,你可以用原向量的长度除以vx和vy。是这样的:
// 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.
用上面的方法你会得到和三角函数sin和cos函数一样的结果。
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:
但是,如果您仍然需要使用原始代码,并希望制作6.12……E-17与0相比,你可以使用epsilon技术来比较浮点数。因此,你可以使用flllowing代码来比较epsilon范围内的任何值:
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.
因此,在[b, b+]范围内的任何偏差都可以成功地与b进行比较,这在浮点运算中是很重要的。