如何停止小数点后四舍五入

时间:2020-03-18 14:27:35

标签: java

我正在尝试计算F的值,其中F = 1 /(1 ^(1/3))+ 1 /(2 ^(1/3))+ ...... + 1 /(600000000 ^(1/3))。我正在使用以下类,但是每个F1,F2,F3和F4的输出返回150000000。仔细检查后,我发现每次将值加到总和时,总和就加1。我如何才能获得非常小的小数位数的准确值,而不是将其变为1?

import java.util.Date;

public class Problem1 {

    public static void main(String[] args) throws InterruptedException{

        //start measuring time
        long begTime = new Date().getTime();

        //Measure execution time of following statements
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        MyThread t3 = new MyThread();
        MyThread t4 = new MyThread();

        t1.n1 = 1;
        t1.n2 = 150000000;

        t2.n1 = 150000001;
        t2.n2 = 300000000;

        t3.n1 = 300000001;
        t3.n2 = 450000000;

        t4.n1 = 450000001;
        t4.n2 = 600000000;

        t1.start();
        t2.start();
        t3.start();
        t4.start();

        t1.join();
        t2.join();
        t3.join();
        t4.join();

        System.out.printf("Value of F1 is %f\n", t1.sum);
        System.out.printf("Value of F2 is %f\n", t2.sum);
        System.out.printf("Value of F3 is %f\n", t3.sum);
        System.out.printf("Value of F4 is %f\n", t4.sum);
        System.out.println();

        System.out.printf("Value of F is %f\n", t1.sum+t2.sum+t3.sum+t4.sum);



        //Compute and print elapsed time
        double timeElapsed = (new Date().getTime() - begTime) * 0.001;
        System.out.printf("Time elapsed = %f secs\n", timeElapsed);

    }
}

public class MyThread extends Thread {

    int n1, n2;
    double sum = 0.0;

    public void run(){

        for (int i=n1; i<= n2;i++){
            sum = sum+ (1/(Math.pow((double) i, (double) (1/3))));


        }

    }

}

3 个答案:

答案 0 :(得分:3)

您可以使用BigDecimal而不是double。 https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html

这可能也有帮助。 Double vs. BigDecimal?

答案 1 :(得分:2)

如果数字类型没有问题,则应使用BigDecimal。

它比Doubles更强大,并且可以放置更多的小数,以及其他诸如本机取舍的操作

https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html

该线程的解释要好得多。

Double vs. BigDecimal?

答案 2 :(得分:0)

这是 float double 的正常行为,如here所示。

考虑使用 BigDecimal 对象,因为它们对于精确的算术运算更强大。