java里Math.abs(x)1e-6是什么意思?

Math.abs(x)<1e-6其实相当于x == 0

1e-6(也就是0.000001)叫做epslon,用来抵消浮点运算中因为误差造成的相等无法判断的情况。它通常是一个非常小的数字(具体多小要看你的运算误差)

在一开始学习c语言的时候,我们就知道计算机在存储数据的时候是使用二进制,而二进制是无法准确存储double数据的。至于是为什么,不要问我,因为我也是新手,而java语言的底层也是c、c++,所以也是同理。

比如说因为精度误差,用十进制举例,我们要算1/3+1/3+1/3 == 1(从数学上说,肯定相等),但是因为精度问题,等号左边算出来是0.3333333+0.3333333+0.3333333 = 0.9999999,存在了误差,右边是1.0000000,那么如果直接用 == ,返回false,我们希望它被视作相等。那么就要两数相减取绝对值小于epslon的办法。

  • 8
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是 Line 类的代码,包括添加的求两条线的交点和求点到线的距离的方法: ```java package JavaPlane; class Line { private Point p1; private Point p2; public Line(Point p1, Point p2) { this.p1 = p1; this.p2 = p2; } public double getLength() { return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2)); } Point getStartPoint() { return p1; } Point getEndPoint() { return p2; } public static boolean point_on_line(Point point, Line line) { Point p1 = Point.sub(line.getStartPoint(), point); Point p2 = Point.sub(line.getEndPoint(), point); return Math.abs(Point.crossProduct(p1, p2)) < 1e-6; } /** * 求两条线的交点 * * @param other 另一条线 * @return 交点,若不存在则返回 null */ public Point getIntersection(Line other) { double x1 = p1.x, y1 = p1.y, x2 = p2.x, y2 = p2.y; double x3 = other.p1.x, y3 = other.p1.y, x4 = other.p2.x, y4 = other.p2.y; double d = (y2 - y1) * (x4 - x3) - (x2 - x1) * (y4 - y3); if (Math.abs(d) < 1e-6) { // 平行或重合 return null; } double ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / d; double ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / d; if (ua < 0 || ua > 1 || ub < 0 || ub > 1) { // 不相交 return null; } double x = x1 + ua * (x2 - x1); double y = y1 + ua * (y2 - y1); return new Point(x, y); } /** * 求点到线的距离 * * @param point 点 * @return 点到线的距离 */ public double distanceToPoint(Point point) { double x1 = p1.x, y1 = p1.y, x2 = p2.x, y2 = p2.y; double x0 = point.x, y0 = point.y; double numerator = Math.abs((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1); double denominator = Math.sqrt(Math.pow(y2 - y1, 2) + Math.pow(x2 - x1, 2)); return numerator / denominator; } } ``` 其中,求两条线的交点的方法使用了向量叉积的知识进行计算。如果两条直线平行或者共线,那么它们没有交点,此时返回 null。否则,计算出交点的坐标并返回。 求点到线的距离的方法使用了点到直线距离公式进行计算。公式中的分子表示点到直线的距离的绝对值,分母表示直线的长度,两者相除即可得到点到直线的距离。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值