有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Vector2类的java旋转问题

我使用了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类是个坏主意吗


共 (1) 个答案

  1. # 1 楼答案

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

    System.out.println(Math.sin(Math.PI));
    // prints 1.2246467991473532E-16 but should be 0
    

    对于90°的倍数旋转,您可以使用rotate90,这将产生精确的结果

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

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