1

I have to implement some relatively complex formulas in a Java application. The inputs to these formulas are include up to 30 or so variables. Some of these variables in their natural form are integers, some are reals with a precision of around 3 to 4 decimal places. I am using commons-math for the functions, but I am wondering about precision and convenience:

Would it be best to convert all variables integers to Double prior to passing to the formula methods. This way there is a consistency within the formulas and secondly can I safely use Double for 3 to 4 dp precision? Is there a "best practice" for implementing complex math in Java?

4

2 回答 2

1

无需将变量转换IntegersDouble. 初始化所有变量,Double因为如果您在公式中有一部分只是将 2 相除Integers并添加到 30 个变量的结果中,那么它将丢失小数位的值。因此,最好将Double小数位数用于产生正确答案的重要数学目的。

于 2015-09-03T03:27:06.213 回答
0

对于精确的浮点计算...我建议使用 BigDecimal。因为 Double 和 Float 以失去精度而闻名。以下片段说明了这个问题。

System.out.println( 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f + 0.1f );
System.out.println( 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d + 0.1d );

1.0000001
0.9999999999999999

将 0.1 乘以十次,您期望得到 1。但事实并非如此。

于 2015-09-03T03:27:27.793 回答