Java 为什么最后一个号码错了?
为什么输出代码中只有最后一个数字出错:Java 为什么最后一个号码错了?,java,math,double,Java,Math,Double,为什么输出代码中只有最后一个数字出错: 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
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)
同样准确 在有限的计算机中,无法用无限的精度表示数字,因此需要进行舍入。您看到的是舍入的效果。这是浮点数的所有用途所固有的
强制链接:使用浮点值进行计算时,由于顺序上的细微差异,舍入错误经常发生。如果你有无限的精度,这将永远不会是一个问题,但计算机不会提供任何时间很快
您最好的选择是确定对您来说重要的精度位数,并在比较它们是否相等之前对值进行剪裁或舍入。由于float/double的限制,舍入错误 你需要定义一些误差范围,然后只要它们在误差范围内,就将它们视为相等的
float f = getFirst();
float g = getSecond();
float epsilon = 0.000005; //Choose something suitably small
if(f-g > epsilon)
//equal
像双精度这样的浮点数精度有限,所以它们的舍入有些随意,这使得一些运算变得困难。我要么把数字的末尾切掉,然后比较它们,要么找出它们之间的差异,然后检查差异是否小于一个小的误差范围(例如0000000001)Hi Alvar-只是一个简短的提示-对于像这样的小代码示例,您完全可以将它们包含在您的问题中。我已经为您添加了粘贴箱中的代码。现在看起来很不错,谢谢!不习惯在问题中植入代码,我习惯于askubuntu.com…@Alvar,两个数字都是错误的,只是一个近似值,一个有一个额外的精确数字。顺便说一句,广场拼错了@对于goldberg论文,使用
Math.sqrt()
的Alvar将比Math.pow(x,0.5)
+1更快更准确。任何严肃的CS人员都必须阅读《我的电脑/Java在一次操作中总结出一个答案》吗?因为我想知道这里的正确答案是什么?@Alvar:两者都不是确切的答案。两者都是四舍五入的。确切的答案有无限多个小数位。是的,但哪一个是最正确的(好吧,两者都错了,但仍然如此。)@Alvar:。第一个版本更好,因为它只需要四舍五入一次,而第二个版本包括三个不精确的步骤。