如何防止小数除法时精度下降?



我用Java编写了下面的程序,以确定数字序列的模式类型。但是,我在划分双打时遇到问题;即使 2 个双精度值非常小(小于小数点后两位;即使只有一个小数位,它也会失去精度(。我打算使用 bigdecimal 类,但我想知道是否有任何更简单的方法或替代方案,因为将 bigdecimal 添加到具有更多函数和变量的大型程序中会很乏味。另外,我还可以进行其他改进吗?

package Numbers;
import javax.swing.*;
public class NumberPatterns {
public static void main(String[] args) {
double a, b, c, d;
a = Double.parseDouble(JOptionPane.showInputDialog("Please enter the value of the first term.")); //first term
b = Double.parseDouble(JOptionPane.showInputDialog("Please enter the value of the second term.")); //second term
c = Double.parseDouble(JOptionPane.showInputDialog("Please enter the value of the third term.")); //third term
d = Double.parseDouble(JOptionPane.showInputDialog("Please enter the value of the fourth term.")); //fourth term
double constantDifference, constantRatio, constantSecondDifference; //Creating variables to verify the sequence characteristic
constantDifference = (b-a) - (d-c); //Constant Difference
System.out.println("b/a value is !! "+b/a);
System.out.println("d/c value is !! "+d/c);
constantRatio = (b/a) - (d/c); //Constant Ratio
constantSecondDifference = ((d-c)-(c-b)) - ((c-b)-(b-a)); // Constant Second Difference
if (constantDifference == 0) // Arthmetic sequence
{
System.out.println("The given sequence is: " + a + "; " + b + "; " + c + "; " + d); // print sequence
System.out.println("This sequence is an arthmetic sequence."); // Sequence type
System.out.println("The constant difference is: " + (b-a)); // Constant difference
System.out.println("The general term is: Tn = " + (a + " + " + (b-a)+ "(n -1)")); //General term
}
else if (constantRatio == 0) // Geometric sequence
{
System.out.println("The given sequence is: " + a + "; " + b + "; " + c + "; " + d); // print sequence
System.out.println("This sequence is an geometric sequence."); // Sequence type
System.out.println("The constant ratio is: " + (b/a)); // Constant ratio
System.out.println("The general term is: Tn = " + a + "*" + (b/a) + "^" + "(n-1)"); //G eneral term
}
else if (constantSecondDifference == 0 && constantDifference != 0) // Quadratic sequence
{
System.out.println("The given sequence is: " + a + "; " + b + "; " + c + "; " + d); // print sequence
System.out.println("This sequence is an quadratic sequence."); // Sequence type
System.out.println("The constant second difference is: " + ((c-b)-(b-a))); // Constant second difference
double x, y, z;                    // The follwing variables are used to calculate the general term 
x = ((c-b)-(b-a));
x = x/2;
y = (b-a) - 3*x;
z = a - x -y;
System.out.println("The general term is: " + x + "n^2 + " + y + "n + (" + z + ")"); // General term
} 
}
}

不幸的是,别无选择。您可以查找的是此标准IEEE 754。所以这甚至不是语言做的事情,而是处理器本身就是这样工作的,你可以期待双精度和浮点数失去精度。获得所需精度的最佳方法是 BigDecimal。如果你不能承受除法,只使用整数也会有所帮助,但是将来你可能需要它,并且仍然需要大十进制。

最新更新