gpt4 book ai didi

java - Vector2 类的旋转问题

转载 作者:行者123 更新时间:2023-12-02 00:54:03 24 4
gpt4 key购买 nike

我使用了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。对任意角度进行精确旋转是很困难的,因为您处理的是精度有限的 float ,但同时必须使用三角函数(sin、cos),这使得我们使用 pi,这是一个无法存储的无理数在计算机上正确:

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

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

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

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

关于java - Vector2 类的旋转问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57835671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com