python division result not true and different results
Question: I am trying to solve fractional knapsack problem.

I have to find items with maximum calories per weight. I will fill my bag up
to defined/limited weight with maximum calories.

Though algorithm is true, I can't find true result because of python division
weirdness

When I try to find items with max calories per weight (python3)

    
    
    print ((calories_list[i]/weight_list[i])*10)
    # calories[i] 500 and weight[i] 30 (they're integers)
    166.66666666666669
    

on the other hand, I opened terminal and typed python3

    
    
    >>> 500/30
    16.666666666666668
    #when multiply with 10, it must be 16.666666666666668 not
    #166.66666666666669
    

as you see, it gives different results

most of all, the important thing is that the real answer

    
    
    500/30=16.6666666667
    

I got stucked here two days ago, please help me

Thanks you


Answer: As explained in the [Python
FAQ](https://docs.python.org/3/faq/design.html#why-are-floating-point-
calculations-so-inaccurate):

> The float type in CPython uses a C double for storage. A float object’s
> value is stored in binary floating-point with a fixed precision (typically
> 53 bits) and Python uses C operations, which in turn rely on the hardware
> implementation in the processor, to perform floating-point operations. This
> means that as far as floating-point operations are concerned, Python behaves
> like many popular languages including C and Java.

You could use the [`decimal`](https://docs.python.org/3/library/decimal.html)
module as an alternative:

    
    
    >>> from decimal import Decimal
    >>> Decimal(500)/Decimal(30)
    Decimal('16.66666666666666666666666667')
    

