为什么最后一个数字错了?
为什么输出代码中只有最后一个数字出错:
public class Test {
public static void main(String[] args) {
System.out.println("Hello world");
System.out.println("I wounder is the sqaure root of (2*3) the
same as the sqaure root of 2 and 3 multiplied.");
double squareroot0 = Math.pow(3*2, 0.5);
double squarroot1 = (Math.pow(3, 0.5) * Math.pow(2, 0.5));
System.out.println("So is it the same?");
System.out.println("is " + squareroot0 + " the equvielant of " +
squarroot1 + "?");
if(squareroot0 == squarroot1) {
System.out.println("Yes number one and number two are
the same, Congrats!");
}else {
System.out.println("No they are not! ");
}
System.out.println(squareroot0);
System.out.println(squarroot1);
}
}
输出:
Hello world
I wonder is the sqaure root of (2*3) the same as the sqaure
root of 2 and 3 multiplied.
So is it the same?
is 2.449489742783178 the equvielant of 2.4494897427831783?
No they are not!
2.449489742783178
2.4494897427831783
数学上它们是等价的,那么发生了什么
Math.sqrt()
和Math.pow(,0.5)
同样准确
# 1 楼答案
像双精度这样的浮点数精度有限,所以它们的舍入有些随意,这使得一些运算变得困难。我要么切掉数字的末尾,然后比较它们,要么找出它们之间的差异,检查差异是否小于一个小的误差范围(例如,0000000001)
# 2 楼答案
在有限的计算机中,你不能用无限的精度来表示数字,所以你需要四舍五入。您看到的是舍入的效果。这是浮点数的所有用途所固有的
强制链接:What Every Computer Scientist Should Know About Floating-Point Arithmetic
# 3 楼答案
由于浮动/双精度限制而产生舍入误差
你需要定义一些误差范围,然后只要它们在误差范围内,就将它们视为相等的
# 4 楼答案
使用浮点值进行计算时,由于顺序上的细微差异,舍入错误经常发生。如果你有无限的精度,这将永远不会是一个问题,但计算机不会提供任何时间很快
最好的办法是确定对您来说重要的精度位数,并在比较它们是否相等之前对值进行剪裁或四舍五入