1

Math.pow() is returning an unexpected result for some inputs.

for ex - below is my code to find the nth root of m

    public class FindRoot {

   static int m,n;

    public static void main(String[] args) {

        findRoot(m,n);

    }

        private static void findRoot(int m, int n) {

        double tempDouble = Math.pow(m, 1.0/n);

        System.out.println(tempDouble);
      }
    }

Now, when i pass m = 9 & n = 2, it is giving expected result i.e. 3.0 but if i pass m = 1000 & n = 3 then i am expected 10.0 but it is giving 9.999999999999998 i.e. unexpected result.

Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55
Ajay
  • 55
  • 3
  • 9
  • You might want to try `0.1 + 0.2` :) – Ray Toal Jan 09 '19 at 04:58
  • 2
    This is how floating point numbers work – Ivan Jan 09 '19 at 04:59
  • Why would expect the result to be rounded up? – Zephyr Jan 09 '19 at 05:01
  • 2
    This is calculated internally as `exp(ln(1000.0) * (1/3.0))` with rounding errors in each step. They accumulate to the result you get. – Henry Jan 09 '19 at 05:03
  • Use `Math.round()` to get rounded value of any value: instead of `System.out.println(tempDouble);` use `System.out.println(Math.round(tempDouble));` –  Jan 09 '19 at 05:04
  • use: System.out.println(Math.ceil(tempDouble)); ; BTW you cant reference non static members in static main class, so edit your question. – Vishwa Ratna Jan 09 '19 at 05:14
  • @thepooran - I can't use Math.round() because for many test cases ...tempDouble value could be 2.8.. or 2.7.. then i will always get an integer value which will be not accepted. – Ajay Jan 09 '19 at 05:14
  • @CommonMan - I can't use Math.ceil() because for many test cases like m = 9 & n = 3...tempDouble value is 2.0800.. then Math.ceil(tempDouble) is returning 3.0 Also, there is no compile-time error with the code so don't worry abut the reference non static members in static main class. – Ajay Jan 09 '19 at 05:20
  • why the hell, this thread is closed?? It needs discussion :/ – Vishwa Ratna Jan 09 '19 at 05:21
  • @Ajay see https://stackoverflow.com/q/11701399/10485339 –  Jan 09 '19 at 05:23

0 Answers0