Search code examples
javamathdivisionsqrt

Java Math not returning the correct answer


I know this general question has been asked more than a few times. However, upon reviewing the threads, a lot of the answers given are pretty specific to the question and don't answer my problem.

If this is a bad or stupidly obvious question, I apologise. I would ask my lecturer but she is unavailable until next week.

The problem I am having is that I have a calculation in a Java program that does not return the correct value and I'm not sure why. The method is :

public int economicOrderQuantity()
//Calculate the Economic Order Quantity of a product
//Only displays the EOQ for one product for the sake of getting it to work
{
    int economicOrderQuantity=0, demandPerWeek, setupPerOrder, costOfInventoryPerWeek, costOfUnit;
    double orderQuantity, orderQuantity1, inventoryByUnit;        

    demandPerWeek = product1.getDemand();
    setupPerOrder = product1.getSetup();
    costOfInventoryPerWeek = product1.getInventory();
    costOfUnit = product1.getUnit();
    inventoryByUnit = costOfInventoryPerWeek / costOfUnit;

    orderQuantity = (2 * demandPerWeek * setupPerOrder) / inventoryByUnit;  //This is the EOQ algorithm 
    orderQuantity1 = Math.sqrt(orderQuantity);
    economicOrderQuantity = (int) Math.round(orderQuantity);    //Typecasts the value to an integer and rounds it

    return economicOrderQuantity;
}

For instance, if the demand rate is 45, the setup cost is 132 and the inventoryByUnit is 0.60, then the EOQ would be 140.71 (rounded to 141). But when I test the code, the value returned is instead 109. I debugged the code and it does the calculation 2*45*132 and returns 11880 and then skips the division by inventoryByUnit and and goes straight to calculating the square root and returns 108.99 (rounded to 109).

Any help or advice as to what I am doing wrong would be greatly appreciated cheers.


Solution

  • (Unless you're using one of those very early Pentium processors, I think it's very safe to assume that Java Math always returns the correct answer.)

    That happens because this:

    inventoryByUnit = costOfInventoryPerWeek / costOfUnit;
    

    Doesn't return what you think it does. It returns 1. A division between two ints will always return the result as an int.

    Try this:

    inventoryByUnit = ((double) costOfInventoryPerWeek) / costOfUnit;
    

    By the way, if it's money that you're dealing with, using doubles is not a very recommended approach. Use BigDecimals instead.