gpt4 book ai didi

Java:点旋转结果不准确

转载 作者:行者123 更新时间:2023-12-01 17:34:09 25 4
gpt4 key购买 nike

我有以下代码...

public class Point {
private double x;
private double y;
static private final double RADTODEG = 180.0d / Math.PI ;
static private final double DEGTORAD = Math.PI / 180.0d;

/**
* Rotates the point by a specific number of radians about a specific origin point.
* @param origin The origin point about which to rotate the point
* @param degrees The number of radians to rotate the point
*/
public void rotateByRadians(Point origin, double radians) {
double cosVal = Math.cos(radians);
double sinVal = Math.sin(radians);

double ox = x - origin.x;
double oy = y - origin.y;

x = origin.x + ox * cosVal - oy * sinVal;
y = origin.y + ox * sinVal + oy * cosVal;
}

/**
* Rotates the point by a specific number of degrees about a specific origin point.
* @param origin The origin point about which to rotate the point
* @param degrees The number of degrees to rotate the point
*/
public void rotateByDegrees(Point origin, double degrees) {
rotateByRadians(origin, degrees * DEGTORAD);
}

/**
* Rotates the point by the specified number of radians about the axis' origin (0,0). To rotate about a specific origin point, see rotateByRadians(Point, double)
* @param radians Measure of radians to rotate the point
*/
public void rotateByRadians(double radians) {
if(isEmpty()) // Since we're rotating about 0,0, if the point is 0,0, don't do anything
return;

double cosVal = Math.cos(radians);
double sinVal = Math.sin(radians);

double newx = x * cosVal - y * sinVal;
double newy = x * sinVal + y * cosVal;

x = newx;
y = newy;
}

/**
* Rotates the point by the specified number of degrees about to the axis' origin (0,0). To rotate about a specific origin point, see rotateByDegrees(Point, double)
* @param degrees Measure of degrees to rotate the point
*/
public void rotateByDegrees(double degrees) {
rotateByRadians(degrees * DEGTORAD);
}

当给定一个点(例如 0,200)时,问题就会出现。调用旋转(绕轴原点 0,0)180 度,它应该是 (0, -200)。 x 坐标不应该改变。然而,它最终是(-2.4492935982947064E-14,-200)。我尝试使用 strictfp 但它没有什么区别。仅当旋转的坐标为零时,这才会影响结果。非零值工作正常。有什么想法为什么这不准确吗?

代码如下:

   Point p = new Point(0.0d, 200.0d);
p.rotateByDegrees(180.0d);
System.out.println(p);

给出输出:

shapelib.Point Object {x: -2.4492935982947064E-14 y: -200.0}

最佳答案

无论好坏, float 学就是这样。来自 http://mindprod.com/jgloss/floatingpoint.html :

"Think of float and double as representing physical measurements. No one would complain if their cabinet maker made a desk 6.000000000001 feet long. Analogously, don’t complain about the inevitable tiny errors in floating point arithmetic results e.g. Math. cos( Math.toRadians( 90 ) ) not coming out bang on zero. ( If you want perfection, use int, long, BigInteger or BigDecimal. )"

关于Java:点旋转结果不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8100986/

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