0
def gas_price(previous, new):
    percent = (new / previous) - 1
    if new == previous:
        decision = 'Full Tank'
    elif percent < .2:
        decision = '3/4 Tank'
    elif .20 <= percent < .80:
        decision = 'Half Tank'
    elif .80 <= percent < 1.00:
        decision = '1/4 Tank'
    else:
        decision = 'Go Home'
    return decision

So here is the function I've created, when I use the input gas_price(100.0, 120.0) the return should be 'Half Tank' because the price has increased by 20% or more. Why is '3/4 Tank' returning when percent = .2?

Miller25
  • 9
  • 2
  • `(120.0 / 100.0) - 1 == 0.19999999999999996` unfortunately! – August Sep 13 '22 at 23:52
  • That is interesting, why does it work out that way? what would be a way to fix that issue? – Miller25 Sep 13 '22 at 23:54
  • 1
    The reason behind this fact, we can't represent 1.2 exactly as a binary fraction. So if you want to work with the fractions like that you can use round function such as `round(percent,2)` the second argument of the round function is the specified number of decimals. – Efe Sep 13 '22 at 23:58
  • Use `percent = round((new / previous) - 1, 1)` – Nick Sep 14 '22 at 00:02
  • 1
    I would recommend you get around this problem by using the in-built python [fractions library](https://docs.python.org/3/library/fractions.html) - convert everything to a `Fraction` before you do your division and comparison to avoid floating point inaccuracies. (Also, with this method you don't have to choose an arbitrary rounding precision) – Oli Sep 14 '22 at 00:08

0 Answers0