舍入错误? [英] Rounding Errors?
问题描述
在我的课程中,我被告知:
In my course, I am told:
连续值大约在内存中表示,因此使用浮点数计算涉及舍入错误。这些是位模式的微小差异;因此,如果
e
和f $ c $,测试
e == f
是不安全的c>是花车。
Continuous values are represented approximately in memory, and therefore computing with floats involves rounding errors. These are tiny discrepancies in bit patterns; thus the test
e==f
is unsafe ife
andf
are floats.
参考Java。
这是真的吗?我已经使用了与 double
和 float
s的比较语句,并且从未遇到过舍入问题。我从未在教科书中读过类似的东西。当然虚拟机会解释这个吗?
Is this true? I've used comparison statements with double
s and float
s and have never had rounding issues. Never have I read in a textbook something similar. Surely the virtual machine accounts for this?
推荐答案
这是真的。
浮点值在内存中以有限位数表示的固有限制。
It is an inherent limitation of how floating point values are represented in memory in a finite number of bits.
例如,此程序打印false:
This program, for instance, prints "false":
public class Main {
public static void main(String[] args) {
double a = 0.7;
double b = 0.9;
double x = a + 0.1;
double y = b - 0.1;
System.out.println(x == y);
}
}
而不是与'=='进行精确比较决定某种程度的精确度,并询问这些数字是否足够接近:
Instead of exact comparison with '==' you usually decide on some level of precision and ask if the numbers are "close enough":
System.out.println(Math.abs(x - y) < 0.0001);
这篇关于舍入错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!