简体   繁体   中英

How can I increase the precision of this n-th root algorithm in Java?

I'm trying to implement the n-th root algorithm for large numbers without using any predefined functions in Java. No sqrt, no pow, no abs, nothing.

The limitations are: 1. The number can be up to 17 digits. 2. The root's order can be from 2 to 10. 3. The precision of the result should be around 10 decimal points.

Is this do-able?

I've read a lot of answers on similar questions on nth root algorithm, Newton's method, other iterative methods, but most of them use either pow, abs, sqrt or other pre-defined functions.

What I've got still has predefined functions and is something I came up with after being inspired from other posts:

public static double getRoot3(double number){
    double guess = 2;
    double possibleRoot = Math.abs((guess*guess)-number);
    while(possibleRoot> 0.009 ){
        possibleRoot = Math.abs((guess*guess)-number);
        guess = ((number/guess)+guess)/2.0;
    }
    return guess;
}
public static void main(String[] args) {
    double number = 12;
    double result = getRoot3(number);
    System.out.println("Number: " + number);
    System.out.println("Square root of " + number + ": " +result);
    System.out.println("Test: " + result * result );
}

This uses a hard-coded number for the test: 12 and the results are as follows:

  • Number: 12.0
  • Square root of 12.0: 3.4641016200294548
  • Test: 12.000000033890693

So it's working, I'm getting a precision of 7 float points, but if I try to increase the preciion by adding zeroes into the while condition it breaks.

I tried to troubleshoot it and it appears that, at somepoint "possibleRoot" suddenly contains an E among the digits and the condition evaluates to false.

How can I increase the precision and how can I extend it for other roots like cubic or more? This one works only for square root right now.

通过使用BigDecimal,您将避免出现double / float精度问题,请参阅Java中BigDecimal的平方根

I don't think you will get it more precise. Java and other languages do have the "Floating Point Problem". It means, that whenever you use floats/doubles it will be slightly different from the original number. That comes from the limitations to represent numbers in memory.

Also, the "E" indicates that the number on the left side of it has to be multiplied by 10^x, where x is the right number of the "E". This will occur when the number has too many digits to display. Example:

125.34E3

= 125.34 * 10^3

= 125.34 * 1000

= 125340.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM