0

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

Semir Umut Kurt
  • 485
  • 5
  • 12
  • What I am saying is that it doesn't give the real answer of division 500/30 which is 16.66666666666667, not 16.66666666666668 – Semir Umut Kurt Jul 30 '16 at 14:36
  • 2
    "This really has nothing to do with Python - you'd see the same behavior in any language using your hardware's binary floating-point arithmetic. First read the docs." See here - maybe it will help. http://stackoverflow.com/a/19473889/5606836 – Jerrybibo Jul 30 '16 at 14:39
  • 3
    Possible duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Ignacio Vazquez-Abrams Jul 30 '16 at 14:42

1 Answers1

0

As explained in the Python FAQ:

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 module as an alternative:

>>> from decimal import Decimal
>>> Decimal(500)/Decimal(30)
Decimal('16.66666666666666666666666667')
noteness
  • 2,440
  • 1
  • 15
  • 15
  • Sorry, you're answer wasn't exactly clear to me. Why does the answer differ between calculations? Does the processor use a different number of bits sometimes? What happens in the hardware that varies the answer? I would assume that even though 500/30 cannot be represented as a binary base, it should still be done the same every time. – Viragos Sep 30 '18 at 00:15