DecimalFormat没有返回正确的数字

时间:2018-06-04 03:33:25

标签: java double decimalformat

以下是此特定任务的提示:设x为任意实数。编写一个程序,通过使用Bisection方法(https://docs.python.org/3/library/functions.html#format)计算x的平方根。请注意,您应该通过a和b的自然选择将此问题减少到二分法(即,用户不需要提供a和b)。请注意,不允许使用Math.powMath.sqrt

问题是当我输入100之类的全部数字(其根是“10.0”而不是控制台返回“9.999997615814209”)或36(“6.0”但控制台返回时)我没有得到正确的答案“5.999997138977051”)。我认为这可能与我对数字进行四舍五入的事实有关,或者仅仅是因为我在使用doubles这一事实,但我并不太了解编程中的数学。谢谢你的帮助。

import java.text.DecimalFormat;
import java.util.Scanner;

public class BisectionMethod {

    public double a = 0;
    public double b;
    public double userInput;
    public int iteration = 0;
    public double midpoint;

    public static void main(String[] args) {
        BisectionMethod testClass = new BisectionMethod();
        System.out.println("Answer: " + testClass.FindAnswer(testClass.FindInput(), testClass.a, testClass.FindInterval()));
    }

    public double FindInput() {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number to find the root for: ");
        userInput = sc.nextDouble();
        while (userInput < 0) {
            System.out.println("Please enter a number bigger than 0: ");
            userInput = sc.nextDouble();
        }
        sc.close();
        return userInput;
    }

    public double FindInterval() {
        while (b * b < userInput) {
            b = b + 1;
        }
        return b;
    }

    public double RoundNumber(double number) {
        //Rounds number to 4 decimal places.
        String pattern = "#.####";
        DecimalFormat formatNumber = new DecimalFormat(pattern);
        double rounded = Double.valueOf(formatNumber.format(number));
        return rounded;
    }

    public double FindAnswer(double number, double interval1, double interval2) {

        midpoint = (interval1 + interval2) / 2;
        double difference = (midpoint * midpoint) - number;

        while (RoundNumber(difference) != 0) {
            midpoint = (interval1 + interval2) / 2;
            difference = (midpoint * midpoint) - number;
            if (midpoint * midpoint < number) {
                interval1 = midpoint;
            } else {
                interval2 = midpoint;
            }
            iteration = iteration + 1;
        }
        System.out.println("Iterations: " + iteration);
        return midpoint;
    }
}

2 个答案:

答案 0 :(得分:0)

努力理解编程中的数学,值得努力。查看这篇文章,因为它可能会提供一些解释,说明为什么你会得到一些意想不到的值 - 可能比你知道的要复杂一些。编程问题只需要坚韧来解决它们,只需继续插入即可。

Double vs. BigDecimal?

答案 1 :(得分:0)

更改

while (RoundNumber(difference) != 0) {

要:

while (difference != 0) {

或者与小ε比较:

while (Math.abs(difference) > 0.0000001) {