Search code examples
javafloating-pointexponentiation

Math.pow using fractional exponents


This is the first code I've ever written. Here's a part of my code which is meant to calculate the side lengths of a cube and tetrahedron after the user gives a value for the volume, however The output is incorrect. I'm pretty sure I have the equations correct, maybe I'm using the Math.pow method incorrectly?

System.out.println("Now, please enter a volume for side or diameter calculation, then press ENTER: ");

volume = input.nextDouble();
cubeSide = Math.pow(volume, (1/3));
sphereDiameter = Math.pow(volume / PI * 6, (1/3));
tetSide = SQRT_2 * Math.pow(3 * volume, (1/3));

System.out.println("");
System.out.println("The Side of your CUBE is : " + cubeSide);
System.out.println("");
System.out.println("The Diameter of your SPHERE is : " + sphereDiameter);
System.out.println("");
System.out.println("The Side of your TETRAHEDRON is : " + tetSide);

Any ideas on how to get correct outputs?


Solution

  • Your question is an instance of this one Division of integers in Java

    Bassically, you need to cast the 1/3 part of your Math.pow() to double, because if you don't do that for default it will take the result as an Integer (always 0).

    For example:

        double volume = 15.34;
        double fraction = (double) 1/3;
        double cubeSide = Math.pow(volume,fraction);
        System.out.println(cubeSide);
    

    Output is

    2.4847066359757295

    Otherwise output is always 1.0. Which is the result of any number rised to the zero.

    As stated in your comment, when the input is:

    1000

    the output should be a whole:

    10

    But actually its:

    9.999999999999998

    The simplest solution to that could be just:

    float roundedValue = Math.round(cubeSide);
    

    And say: that's not my problem. But we want to understand what that's happening. As most things in this world, you are not the first one to face this problem. Let's do some research and find that there in StackOverFlow it have been asked:

    In the first link, its suggested to read What Every Computer Scientist Should Know About Floating-Point Arithmetic.

    I wont repeat what those wise people whom know a lot more than me said, so I highly recommend to you to read the above links.