Java 向量2类的旋转问题

Java 向量2类的旋转问题,java,libgdx,Java,Libgdx,我使用了Vector2类,并用它进行了一些旋转过程。但结果并不是我所期望的。我不知道有什么问题。看看我的代码和输出 Vector2 vec; vec = new Vector2(5, 0); vec.setAngle(90.0f); // I expected output to be "x = 0" // But it prints "x = -2.1855695E-7" This is problematic. System.out.println("x = " + vec.x); //

我使用了
Vector2
类,并用它进行了一些旋转过程。但结果并不是我所期望的。我不知道有什么问题。看看我的代码和输出

Vector2 vec;

vec = new Vector2(5, 0);
vec.setAngle(90.0f);
// I expected output to be "x = 0"
// But it prints "x = -2.1855695E-7" This is problematic.
System.out.println("x = " + vec.x);
// I expected output to be "y = 5"
// And it prints "y = 5" OK. No problem.
System.out.println("y = " + vec.y);

vec = new Vector2(5, 0);
vec.setAngle(180.0f);
// I expected output to be "x = -5"
// And it prints "x = -5" OK. No problem.
System.out.println("x = " + vec.x);
// I expected output to be "y = 0"
// But it prints "y = -4.371139E-7" This is problematic.
System.out.println("y = " + vec.y);

vec = new Vector2(5, 0);
vec.setAngle(270.0f);
// I expected output to be "x = 0"
// But it prints "x = 5.9624405E-8" This is problematic.
System.out.println("x = " + vec.x);
// I expected output to be "y = -5"
// And it prints "y = -5" OK. No problem.
System.out.println("y = " + vec.y);

vec = new Vector2(5, 0);
vec.setAngle(360.0f);
// I expected output to be "x = 5"
// And it prints "x = 5" OK. No problem.
System.out.println("x = " + vec.x);
// I expected output to be "y = 0"
// But it prints "y = 8.742278E-7" This is problematic.
System.out.println("y = " + vec.y);

为什么有些输出不是我期望的?使用
Vector2
类进行旋转处理是否不好?

得到的结果接近正确值0。 对任意角度进行精确旋转是很困难的,因为您处理的是精度有限的浮点数,但同时必须使用三角函数(sin,cos),这使我们使用pi,一个无法正确存储在计算机上的无理数:

System.out.println(Math.sin(Math.PI));
// prints 1.2246467991473532E-16 but should be 0
对于90°的倍数旋转,您可以使用
rotate90
,这将产生精确的结果

对于任意角度,你将不得不接受一个近似值,你可以通过在比较中允许一个小的增量来解决这个问题

为了获得更接近精确结果的近似值,您可以尝试使用双精度而不是浮点数来编写旋转函数,以获得更高的精度。

甚至
(float)1
也不完全是1。与非理性主义者合作是无关紧要的。