问题描述
我有一个问题,我需要在我的java程序中的一个函数。我想检查数字的总量,一个'double'变量。 (例如:5应该返回1,5.0034应该返回5,2.04应该返回3.)我的功能是这样:
I got a little problem with a function I need in my java progam. I want to check the total amount of digits, a 'double' variable has. (e.g.: 5 should return 1, 5.0034 should return 5, and 2.04 should return 3.) My function is this:
private int getDoubleLength (double a) {
int len = 0;
while (a != (int) a) {
a *= 10;
}
while (a > 1) {
len ++;
a/=10;
}
System.out.println(String.format("Double %f has %d digits.",a,len));
return len;
}
现在这个工作完美,但是当我做一些数学计算时,双精度的微小误差:我将10除以cos(60),即0,5。答案应该是20.0,但程序给了一个20.000000000000004(那个数,我复制它)。我的while循环卡住,程序挂起。
Now this works perfectly, but when I am making some mathematical calculations, you get the slight errors of doubles: I divide 10 by cos(60), which is 0,5. The answer should be 20.0, but the program gives a 20.000000000000004 (that number, I copied it). My while loop gets stuck, and the program hangs.
任何想法? (或其他检查数字数字的绝佳解决方案!)
Any ideas? (Or other great solutions for checking the digits of a number!)
推荐答案
然后双击和浮动和操作不准确与代数计算相比总会有微小的误差。如果你使用余弦等,那么你总是必须处理这些舍入误差,任何书或网络文本数值分析应该描述。如果您使用简单的宗教操作,请查看
Doubles and floats and operations on then are not exact so there will always bee slight errors compared with algebraic calculations. If you are using cosines etc then you will always have to deal with these rounding errors which any book or web text on numerical analysis should describe. If you are using simple aritmetic operations look at java.lang.BigDecimal
有关浮点值如何存储的详细信息,请参阅
For details on how floating point values are stored.see What Every Computer Scientist Should Know About Floating-Point Arithmetic
这篇关于获取双变量中的数字时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!