java - 浮点精度

标签 java floating-point

我正在编写一种方法,以 a*x+b*y=1 的形式计算二维线的方程。

//Given two points, find the equation of the line by solving two linear equations and then test the result. (For simplicity, assume that delta !=0 here)

private boolean solveAndRetry(float x1,float y1, float x2,float y2) {
        float delta = x1 * y2 - x2 * y1;
        float deltaA = y2 - y1;
        float deltaB = x1 - x2;

        float a = deltaA / delta;
        float b = deltaB / delta;
        float c = 1;

        //test
        if (a * x2 + b * y2 == c) {
        System.out.println("ok");
            return true;
        }
        else {
            System.out.println(a * x2 + b * y2-c);
            return false;
        }
    }

当我运行它时,我期望所有结果都是“ok”,但事实并非如此,我不知道为什么

public static void main(String[] args) {
        for (float x = 0; x < 10; x += 0.01f) {
            solveAndRetry(1, -1, x, 2);
        }
    }

这是结果中的一些行

ok
ok
ok
ok
ok
ok
ok
ok
-5.9604645E-8
ok
-5.9604645E-8
ok
ok
ok
1.1920929E-7
ok
ok
-5.9604645E-8
ok

最佳答案

float 的精度为 6 到 7 位十进制数字。由于舍入误差无法避免,因此您的结果已尽其所能。

通常,您永远不会比较 float 是否相等。始终使用间隔比较,而不是 x == y:

Math.abs(x - y) < eps

对于适当选择的 eps。

关于java - 浮点精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21063496/

相关文章:

java - IntelliJ 可以隐藏 Java 样板代码吗? getter 和 setter

python - numpy 或 scipy 有哪些可能的计算可以返回 NaN?

java - 设计模式——调度员

java - 将 TXT 文件拖放到 TextArea 中

java - 将 MySQL 中的 CHAR(0) 映射到 Hibernate 中的 boolean 值

java - JAXB 是否支持 xsd :restriction?

c - 在有限的 16 字节字符串上将 IEEE 754-1985 双倍写入 ASCII

php - 使用 "<="或 ">="比较 float 是否理想?

java浮点精度(0.1+0.2+...+1.00 ..or.. 1.00+0.99+0.98+...+0.1)

C++,如何优化浮点算术运算?