Android - 精确的数学计算 [英] Android - exact mathematical calculation
问题描述
我遇到了问题,我正在开发一个能够进行数学计算的应用程序。这些计算必须准确(或者说明显不是错误的)
I have got a Problem, I am developing an Application which should be able to do some mathematic calculations. These calculations have to be exact (or rather not obviously wrong)
但这个简单的代码
double a = 3.048d;
double b = 1000d;
double c = a / b;
给我一个错误的结果c不是预期的0.003048而是0.0030480000000000004这显然是错误的。
gives me a wrong result c is not 0.003048 as expected instead it is 0.0030480000000000004 which is obviously wrong.
double d = 3.048 / 1000;
第二个代码snipet给出了正确的结果。
this second code-snipet gives the correct result.
我知道用计算机计算时所有的浮点运算都不准确,但我不知道如何解决这个问题。
I am aware that all floatingpoint arithmetic is not exact when calculating with computers but I don't know how to solve this problem.
提前感谢!
Ludwig
thanks in advance!
Ludwig
开发:
- Android 2.2
Testdevice:
- HTC Desire
Developing for:
- Android 2.2
Testdevice:
- HTC Desire
推荐答案
什么 BigDecimal <需要用于精确的精确度/ a>对象:
What you need to use for exact percision is the BigDecimal object:
BigDecimal a = new BigDecimal("3.048");
BigDecimal b = new BigDecimal(1000);
BigDecimal c = a.divide(b);
System.out.println(c); //0.003048
这篇关于Android - 精确的数学计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!